public void InitializeImagesLibrary()
    {
        Debug.Log(arTrackingImageManager + ":" + arTrackingImageManager.descriptor);
        if (arTrackingImageManager)
        {
            goToImage.Clear();
            MutableRuntimeReferenceImageLibrary runtimeImageLibrary = arTrackingImageManager.CreateRuntimeLibrary() as MutableRuntimeReferenceImageLibrary;

            if (runtimeImageLibrary == null)
            {
                Debug.LogError(gameObject.name + ":Library is nullable");
                return;
            }

            foreach (ObjectToImage item in images)
            {
                Debug.Log(item.image.name);
                goToImage.Add(item.image.name, item.@object);
                runtimeImageLibrary.ScheduleAddImageJob(item.image, item.image.name, item.image.width / 1000f);// Первая ошибка, размеры текстуры я делил на цельный int от чего оно округлялось до ближайшего цельного числа, к примеру "201f/1000 = 0" а вот "201f/1000f = 0.201" не забывайте про логику хранения чисел в памяти компьютера
            }

            arTrackingImageManager.referenceLibrary        = runtimeImageLibrary;
            arTrackingImageManager.maxNumberOfMovingImages = 2;
            arTrackingImageManager.trackedImagesChanged   += ArTrackingImageManager_trackedImagesChanged;
            arTrackingImageManager.enabled = true;
        }
        else
        {
            Debug.LogError("Not Supports Mutable Library");
        }
    }
    private IEnumerator AddImageJob()
    {
        yield return(null);



        Logger.Log("Adding image\n");

        Logger.Log("Job Starting...");

        var firstGuid  = new SerializableGuid(0, 0);
        var secondGuid = new SerializableGuid(0, 0);

        //   XRReferenceImage newImage = new XRReferenceImage(firstGuid, secondGuid, new Vector2(0.1f, 0.1f), Guid.NewGuid().ToString(), texture2D);
        addedImageCount++;
        XRReferenceImage newImage = new XRReferenceImage(firstGuid, secondGuid, new Vector2(0.1f, 0.1f), addedImageCount.ToString(), currentTexture);

        try
        {
            // loadingGameObj.SetActive(true);

            // Debug.Log("new image naame"+newImage.ToString()) ;

            MutableRuntimeReferenceImageLibrary mutableRuntimeReferenceImageLibrary = trackedImageManager.referenceLibrary as MutableRuntimeReferenceImageLibrary;



            var jobHandle = mutableRuntimeReferenceImageLibrary.ScheduleAddImageJob(currentTexture, addedImageCount.ToString(), 0.1f);

            while (!jobHandle.IsCompleted)
            {
                Logger.Log("Job Running...");
            }
            Logger.Log("job finsihed added to dictionary");

            //remove things from memory
            currentTexture = null;
            Resources.UnloadUnusedAssets();
            GC.Collect();

            //logging
            Logger.Log("image downloaded and added to library");
            Logger.Log("image count" + mutableRuntimeReferenceImageLibrary.count);

            //trigger event to convey success message
            Eventbus.Instance.TriggerEvent(SystemStatus.ImageAddedToLibrary);
            //tell the controller that you had added image to library and send this id to controller
            imageTargetController.OnImageAddedToLibrary(newImage.name);
        }
        catch (Exception e)
        {
            Eventbus.Instance.TriggerEvent(SystemStatus.FailedToAddToLibrary);
            Logger.Log(e.ToString());
        }
    }
Esempio n. 3
0
        /// <summary>
        /// this addes images target runtime to the xrreference library through unity job system
        /// </summary>
        /// <param name="texture2D"></param>
        /// <returns></returns>
        public IEnumerator AddImageJob(ImageTargetVideoUrlTemplate t)
        {
            yield return(null);



            print("Adding image\n");

            print("Job Starting...");

            var firstGuid  = new SerializableGuid(0, 0);
            var secondGuid = new SerializableGuid(0, 0);

            //   XRReferenceImage newImage = new XRReferenceImage(firstGuid, secondGuid, new Vector2(0.1f, 0.1f), Guid.NewGuid().ToString(), texture2D);
            addedImageCount++;
            XRReferenceImage newImage = new XRReferenceImage(firstGuid, secondGuid, new Vector2(0.1f, 0.1f), addedImageCount.ToString(), currentDownloadedTexture);

            try
            {
                loadingGameObj.SetActive(true);

                Debug.Log("new image naame" + newImage.ToString());

                MutableRuntimeReferenceImageLibrary mutableRuntimeReferenceImageLibrary = trackImageManager.referenceLibrary as MutableRuntimeReferenceImageLibrary;



                var jobHandle = mutableRuntimeReferenceImageLibrary.ScheduleAddImageJob(currentDownloadedTexture, addedImageCount.ToString(), 0.1f);

                while (!jobHandle.IsCompleted)
                {
                    print("Job Running...");
                }

                loadingGameObj.SetActive(false);
                Debug.Log("job finsihed added to dictionary");
                //  referenceImageAddedEvent?.Invoke(newImage,t);
                GetComponent <DynamicImgVideoSpawner>().OnReferenceImageAdded(newImage, t);

                currentDownloadedTexture = null;
                Resources.UnloadUnusedAssets();
                GC.Collect();
                //image downloaded and added to library
                //  imageTargetUrlGetter.OnUnityEntered();

                print("image downloaded and added to library");
                print("image count" + mutableRuntimeReferenceImageLibrary.count);
                //print("name da mame " + newImage.name);
            }
            catch (Exception e)
            {
                print(e.ToString());
            }
        }
Esempio n. 4
0
        public void AddMarker(Texture2D sampleMarker, string sampleMarkerName, GameObject samplePrefab)
        {
            if (!isARInitialize)
            {
                DebugText("AR state is not ready..");
                return;
            }

            //if (CheckMarkerExists(sampleMarkerName))
            //{
            //    DebugText("Marker name " + sampleMarkerName + " is already exist..");
            //    return;
            //}

            DebugText("Begin add marker..");
            DebugImage(MainAPI.Instance.SpriteFromTexture2D(sampleMarker));

            if (IsSupportsMutableLibrary())
            {
                DebugText("supportsMutableLibrary is enabled..");

                var texture = sampleMarker;
                DebugText("Marker name: " + sampleMarkerName);

                ResetRuntimeImageLibrary();

                Unity.Jobs.JobHandle jobHandle = myRuntimeReferenceImageLibrary.ScheduleAddImageJob(texture, sampleMarkerName, 0.2f);
                jobHandle.Complete();

                //myRuntimeReferenceImageLibrary

                if (myRuntimeReferenceImageLibrary != null)
                {
                    DebugText("myRuntimeReferenceImageLibrary: " + myRuntimeReferenceImageLibrary.count);
                    DebugText("supportedTextureFormatCount: " + myRuntimeReferenceImageLibrary.supportedTextureFormatCount);

                    mARTrackedImageManager.referenceLibrary = myRuntimeReferenceImageLibrary;
                }
                else
                {
                    DebugText("myRuntimeReferenceImageLibrary is NULL");
                }
                mARTrackedImageManager.maxNumberOfMovingImages = 1;
                mARTrackedImageManager.trackedImagePrefab      = samplePrefab;
                mARTrackedImageManager.enabled = true;
            }
            else
            {
                DebugText("supportsMutableLibrary is disabled");
            }
        }
    public IEnumerator AddImageJob(Texture2D texture2D)
    {
        yield return(null);

        debugLog.text = string.Empty;

        debugLog.text += "Adding image\n";

        jobLog.text = "Job Starting...";

        var firstGuid  = new SerializableGuid(0, 0);
        var secondGuid = new SerializableGuid(0, 0);

        XRReferenceImage newImage = new XRReferenceImage(firstGuid, secondGuid, new Vector2(0.1f, 0.1f), Guid.NewGuid().ToString(), texture2D);

        try
        {
            MutableRuntimeReferenceImageLibrary mutableRuntimeReferenceImageLibrary = trackImageManager.referenceLibrary as MutableRuntimeReferenceImageLibrary;

            debugLog.text += $"TextureFormat.RGBA32 supported: {mutableRuntimeReferenceImageLibrary.IsTextureFormatSupported(TextureFormat.RGBA32)}\n";

            debugLog.text += $"TextureFormat size: {texture2D.width}px width {texture2D.height}px height\n";

            var jobHandle = mutableRuntimeReferenceImageLibrary.ScheduleAddImageJob(texture2D, Guid.NewGuid().ToString(), 0.1f);

            while (!jobHandle.IsCompleted)
            {
                jobLog.text = "Job Running...";
            }

            jobLog.text    = "Job Completed...";
            debugLog.text += $"Job Completed ({mutableRuntimeReferenceImageLibrary.count})\n";
            debugLog.text += $"Supported Texture Count ({mutableRuntimeReferenceImageLibrary.supportedTextureFormatCount})\n";
            debugLog.text += $"trackImageManager.trackables.count ({trackImageManager.trackables.count})\n";
            debugLog.text += $"trackImageManager.trackedImagePrefab.name ({trackImageManager.trackedImagePrefab.name})\n";
            debugLog.text += $"trackImageManager.maxNumberOfMovingImages ({trackImageManager.maxNumberOfMovingImages})\n";
            debugLog.text += $"trackImageManager.supportsMutableLibrary ({trackImageManager.subsystem.SubsystemDescriptor.supportsMutableLibrary})\n";
            debugLog.text += $"trackImageManager.requiresPhysicalImageDimensions ({trackImageManager.subsystem.SubsystemDescriptor.requiresPhysicalImageDimensions})\n";
        }
        catch (Exception e)
        {
            if (texture2D == null)
            {
                debugLog.text += "texture2D is null";
            }
            debugLog.text += $"Error: {e.ToString()}";
        }
    }
        /// <summary>
        /// Asynchronously adds <paramref name="texture"/> to <paramref name="library"/>.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Image addition can take some time (several frames) due to extra processing that
        /// must occur to insert the image into the library. This is done using
        /// the [Unity Job System](https://docs.unity3d.com/Manual/JobSystem.html). The returned
        /// [JobHandle](https://docs.unity3d.com/ScriptReference/Unity.Jobs.JobHandle.html) can be used
        /// to chain together multiple tasks or to query for completion, but may be safely discarded if you do not need it.
        /// </para><para>
        /// This job, like all Unity jobs, can have dependencies (using the <paramref name="inputDeps"/>). If you are adding multiple
        /// images to the library, it is not necessary to pass a previous <c>ScheduleAddImageJob</c> JobHandle as the input
        /// dependency to the next <c>ScheduleAddImageJob</c>; they can be processed concurrently.
        /// </para><para>
        /// The bytes of the <paramref name="texture"/> are copied, so the texture may be safely
        /// destroyed after this method returns.
        /// </para>
        /// </remarks>
        /// <param name="library">The <c>MutableRuntimeReferenceImageLibrary</c> being extended.</param>
        /// <param name="texture">The <c>Texture2D</c> to use as image target.</param>
        /// <param name="name">The name of the image.</param>
        /// <param name="widthInMeters">The physical width of the image, in meters.</param>
        /// <param name="inputDeps">Input job dependencies (optional).</param>
        /// <returns>A [JobHandle](https://docs.unity3d.com/ScriptReference/Unity.Jobs.JobHandle.html) which can be used
        /// to chain together multiple tasks or to query for completion. May be safely discarded.</returns>
        /// <exception cref="System.InvalidOperationException">Thrown if <see cref="library"/> is <c>null</c>.</exception>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="texture"/> is <c>null</c>.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown if <paramref name="texture"/> is not readable.</exception>
        public static JobHandle ScheduleAddImageJob(
            this MutableRuntimeReferenceImageLibrary library,
            Texture2D texture,
            string name,
            float?widthInMeters,
            JobHandle inputDeps = default(JobHandle))
        {
            if (ReferenceEquals(library, null))
            {
                throw new ArgumentNullException(nameof(library));
            }

            if (texture == null)
            {
                throw new ArgumentNullException(nameof(texture));
            }

            if (!texture.isReadable)
            {
                throw new InvalidOperationException("The texture must be readable to be used as the source for a reference image.");
            }

            var imageBytesCopy = new NativeArray <byte>(texture.GetRawTextureData <byte>(), Allocator.Persistent);

            try
            {
                Nullable <Vector2> size = null;
                if (widthInMeters.HasValue)
                {
                    size = new Vector2(widthInMeters.Value, widthInMeters.Value * (float)texture.height / (float)texture.width);
                }

                var referenceImage = new XRReferenceImage(SerializableGuid.empty, SerializableGuid.empty, size, name, texture);
                var jobHandle      = library.ScheduleAddImageJob(imageBytesCopy, new Vector2Int(texture.width, texture.height), texture.format, referenceImage, inputDeps);
                new DeallocateJob {
                    data = imageBytesCopy
                }.Schedule(jobHandle);
                return(jobHandle);
            }
            catch
            {
                imageBytesCopy.Dispose();
                throw;
            }
        }
    public IEnumerator AddImageJob(Texture2D texture2D)
    {
        yield return(null);

        Debug.Log("tex name " + texture2D.name);
        var firstGuid  = new SerializableGuid(0, 0);
        var secondGuid = new SerializableGuid(0, 0);

        //   XRReferenceImage newImage = new XRReferenceImage(firstGuid, secondGuid, new Vector2(0.1f, 0.1f), Guid.NewGuid().ToString(), texture2D);
        addedImageCount++;
        XRReferenceImage newImage = new XRReferenceImage(firstGuid, secondGuid, new Vector2(0.1f, 0.1f), addedImageCount.ToString(), texture2D);

        // loadingCanvas.SetActive(true);
        try
        {
            Debug.Log(newImage.ToString());

            MutableRuntimeReferenceImageLibrary mutableRuntimeReferenceImageLibrary = trackImageManager.referenceLibrary as MutableRuntimeReferenceImageLibrary;



            var jobHandle = mutableRuntimeReferenceImageLibrary.ScheduleAddImageJob(texture2D, addedImageCount.ToString(), 0.1f);

            while (!jobHandle.IsCompleted)
            {
                print("Job Running...");
            }
            //loadingCanvas.SetActive(false);

            Debug.Log("job finsihed added to dictionary");
            // referenceImageAddedEvent?.Invoke(newImage, t);
            //image downloaded and added to library
            //  imageTargetUrlGetter.OnUnityEntered();
            print("image downloaded and added to library");

            //print("name da mame " + newImage.name);
            Destroy(texture2D);
            GC.Collect();
        }
        catch (Exception e)
        {
            print(e.ToString());
        }
    }
Esempio n. 8
0
 private void AddMarkerToLibrary(Texture2D texture, string name)
 {
     mutableLibrary.ScheduleAddImageJob(texture, name, 0.1f);
 }
Esempio n. 9
0
    // Descarga los targets utilizando las urls de entrada y los
    // añade a la colleccion/libreria de targets para que AR Foundation
    // pueda detectarlas. El nombre de cada target es el id al que esta
    // vinculado.
    private IEnumerator DownloadAndAddTargetsFromUrl(List <string> links, List <string> ids)
    {
        // Empareja el id con su textura.
        // image.item1 es el id
        // image.item2 es la textura2D
        List <Tuple <string, Texture2D> > allImages = new List <Tuple <string, Texture2D> >();

        // Descarga de imagenes
        for (int h = 0; h < links.Count; h++)
        {
            UnityWebRequest request = UnityWebRequestTexture.GetTexture(links[h]);
            yield return(request.SendWebRequest());

            Texture2D texture2D;


            if (request.isNetworkError || request.isHttpError)
            {
                Debug.Log(request.error);
            }
            else
            {
                debugLog.text += "Descarga de Imagen exitosa.\n";
                texture2D      = ((DownloadHandlerTexture)request.downloadHandler).texture;
                allImages.Add(new Tuple <string, Texture2D>(ids[h], texture2D));
            }
        }


        // Creacion de coleccion/libreria de targets para AR foundation.
        try
        {
            trackImageManager.referenceLibrary        = trackImageManager.CreateRuntimeLibrary(runtimeImageLibrary);
            trackImageManager.maxNumberOfMovingImages = 3;
            trackImageManager.trackedImagePrefab      = prefabOnTrack;


            trackImageManager.enabled = true;

            MutableRuntimeReferenceImageLibrary mutableRuntimeReferenceImageLibrary = trackImageManager.referenceLibrary as MutableRuntimeReferenceImageLibrary;

            debugLog.text += $"TextureFormat.RGBA32 supported: {mutableRuntimeReferenceImageLibrary.IsTextureFormatSupported(TextureFormat.RGBA32)} \n";

            // Recorre la lista de pares para añadir la textura2D/Target
            // a la mutableRuntimeReferenceImageLibrary con el id como nombre.
            // image.item1 es el id
            // image.item2 es la textura2D
            foreach (var image in allImages)
            {
                Texture2D texture2D = image.Item2;
                debugLog.text += $"TextureFormat size: {texture2D.width}px width {texture2D.height}px height \n";

                var jobHandle = mutableRuntimeReferenceImageLibrary.ScheduleAddImageJob(texture2D, image.Item1, 0.1f);

                while (!jobHandle.IsCompleted)
                {
                    debugLog.text += "Job Running... \n";
                    Task.Delay(100).Wait();
                }
            }
        }
        catch (Exception e)
        {
            debugLog.text += e.ToString() + "\n";
        }
    }