Beispiel #1
0
        IntPtr CreateImageDatabase(XRReferenceImageLibrary library)
        {
            if (!Api.AtLeast11_3())
            {
                throw new NotSupportedException($"Image libraries require iOS 11.3 or newer.");
            }

            if (library == null)
            {
                return(Init());
            }

            using var managedReferenceImages = library.ToNativeArray(Allocator.Temp);
            using var bundle = library.GetNSBundle();
            if (bundle == null)
            {
                throw new InvalidOperationException($"Could not create reference image library '{library.name}'. Unable to create resource bundle.");
            }

            using var groupName       = library.GetARResourceGroupName();
            using var referenceImages = ARReferenceImage.GetReferenceImagesInGroupNamed(groupName, bundle);
            if (referenceImages.Count != managedReferenceImages.Length)
            {
                throw new InvalidOperationException($"The number of images in the {nameof(XRReferenceImageLibrary)} named '{library.name}' ({library.count}) does nat match the number of images in the native reference image data ({referenceImages.Count}). The {nameof(XRReferenceImageLibrary)} may need to be re-exported for iOS.");
            }

            return(InitWithImages(referenceImages.AsIntPtr(), managedReferenceImages.AsNativeView()));
        }
        public static byte[] BuildDb(XRReferenceImageLibrary library)
        {
            var tempDirectory = Path.Combine(Path.GetTempPath(), GetTempFileNameWithoutExtension());

            try
            {
                Directory.CreateDirectory(tempDirectory);
                var imageListPath = library.ToInputImageListPath(tempDirectory);
                var dbPath        = Path.Combine(tempDirectory, $"{GetTempFileNameWithoutExtension()}.imgdb");
                var(stdOut, stdErr, exitCode) = BuildDb(imageListPath, dbPath);

                if (exitCode != 0)
                {
                    throw new BuildDatabaseFailedException(exitCode, stdErr);
                }

                if (!File.Exists(dbPath))
                {
                    throw new EmptyDatabaseException(stdOut, stdErr);
                }

                return(File.ReadAllBytes(dbPath));
            }
            finally
            {
                if (Directory.Exists(tempDirectory))
                {
                    Directory.Delete(tempDirectory, true);
                }
            }
        }
 static void ClearReferenceImageLibraryDataStores()
 {
     foreach (var library in XRReferenceImageLibrary.All())
     {
         library.ClearDataStore();
     }
 }
Beispiel #4
0
    public void GenerateLibFromSceneSetting()
    {
        NYImageTracker[] trackers = GameObject.FindObjectsOfType <NYImageTracker>();

        Transform[]             objs   = new Transform[trackers.Length];
        XRReferenceImageLibrary newLib = ScriptableObject.CreateInstance <XRReferenceImageLibrary>();

        string debugText = "Found " + trackers.Length + " Trackers in Scene:\n";

        for (int i = 0; i < trackers.Length; i++)
        {
            debugText += "  " + trackers[i].gameObject.name + "\n";
            objs[i]    = trackers[i].transform;

            XRReferenceImageLibraryExtensions.Add(newLib);
            XRReferenceImageLibraryExtensions.SetName(newLib, i, trackers[i].name);
            XRReferenceImageLibraryExtensions.SetTexture(newLib, i, trackers[i].trackerImage, false);
            XRReferenceImageLibraryExtensions.SetSpecifySize(newLib, i, true);
            XRReferenceImageLibraryExtensions.SetSize(newLib, i, trackers[i].physicalSize);
        }

        string targetPath = Resources.Load <ARFoundationHelperSettings>("HelperSettings").GeneratedLibrarySavePath;

        AssetDatabase.CreateAsset(newLib, targetPath + "generated-lib.asset");

        ((NYImageTrackerManager)target).targetLib   = newLib;
        ((NYImageTrackerManager)target).trackerObjs = objs;

        Debug.Log(debugText);
    }
 static void UpdateRefImage(XRReferenceImageLibrary xrReferenceImageLibrary, int index, MarsMarkerDefinition marsMarkerDefinition)
 {
     xrReferenceImageLibrary.SetName(index, marsMarkerDefinition.Label);
     xrReferenceImageLibrary.SetSpecifySize(index, marsMarkerDefinition.SpecifySize);
     xrReferenceImageLibrary.SetSize(index, marsMarkerDefinition.Size);
     xrReferenceImageLibrary.SetTexture(index, marsMarkerDefinition.Texture, true);
 }
        public static unsafe NSBundle GetNSBundle(this XRReferenceImageLibrary library)
        {
            // If no data exists in the XRReferenceImageLibrary, then try to look it up in the main bundle
            if (!library.dataStore.TryGetValue(ARKitPackageInfo.identifier, out var assetCatalogData))
            {
                var mainBundle = NSBundle.mainBundle;
                NSObject.Retain(mainBundle);
                return(mainBundle);
            }

            fixed(void *data = assetCatalogData)
            {
                using var mainBundleIdentifier = NSBundle.mainBundle.bundleIdentifier;
                using var bundleIdentifier     = new NSMutableString(mainBundleIdentifier);
                using var uuid = library.guid.ToNSString();

                bundleIdentifier.Append(uuid);

                return(new NSBundle(bundleIdentifier, new NativeView
                {
                    data = data,
                    count = assetCatalogData.Length
                }));
            }
        }
        static bool ContentsSync(MarsMarkerLibrary marsMarkerLibrary, XRReferenceImageLibrary xrReferenceImageLibrary)
        {
            var needsSave = false;

            // Find all changes and synchronize
            var referenceImages = new Dictionary <Guid, XRReferenceImage>();

            foreach (var xrRefImage in xrReferenceImageLibrary)
            {
                referenceImages.Add(xrRefImage.guid, xrRefImage);
            }

            var markersToAdd = new List <MarsMarkerDefinition>();
            var markersToUpdateDictionary = new Dictionary <MarsMarkerDefinition, XRReferenceImage>();

            foreach (var marsDefinition in marsMarkerLibrary)
            {
                if (referenceImages.ContainsKey(marsDefinition.MarkerId))
                {
                    var refImage = referenceImages[marsDefinition.MarkerId];
                    if (refImage.name != marsDefinition.Label || refImage.specifySize != marsDefinition.SpecifySize ||
                        refImage.size != marsDefinition.Size || refImage.texture != marsDefinition.Texture)
                    {
                        markersToUpdateDictionary.Add(marsDefinition, refImage);
                        needsSave = true;
                    }

                    referenceImages.Remove(marsDefinition.MarkerId);
                }
                else
                {
                    markersToAdd.Add(marsDefinition);
                    needsSave = true;
                }
            }

            // Whatever is left in referenceImages needs to be deleted, since none of the marker definitions match
            needsSave = needsSave || referenceImages.Count > 0;
            foreach (var refImageEntry in referenceImages)
            {
                var index = xrReferenceImageLibrary.indexOf(refImageEntry.Value);
                xrReferenceImageLibrary.RemoveAt(index);
            }

            foreach (var marsMarkerDefinition in markersToAdd)
            {
                var refImage = AddRefImageFromMarker(xrReferenceImageLibrary, marsMarkerDefinition);
                marsMarkerLibrary.SetGuid(marsMarkerLibrary.IndexOf(marsMarkerDefinition), refImage.guid);
            }

            foreach (var dictEntry in markersToUpdateDictionary)
            {
                var index = xrReferenceImageLibrary.indexOf(dictEntry.Value);
                UpdateRefImage(xrReferenceImageLibrary, index, dictEntry.Key);
            }

            return(needsSave);
        }
Beispiel #8
0
        unsafe void DeserializeImageDatabaseFile(XRReferenceImageLibrary serializedLibrary)
        {
            var libraryPath = MagicLeapImageTrackingSubsystem.GetDatabaseFilePathFromLibrary(serializedLibrary);

            if (!File.Exists(libraryPath))
            {
                throw new ArgumentException($"Serialized Image Tracking Library at '{libraryPath}' doesn't exist.");
            }

            var bytes = File.ReadAllBytes(libraryPath);

            if (bytes.Length < sizeof(ulong))
            {
                throw new ArgumentException($"Serialized Image Tracking Library at '{libraryPath}' has no image data within it.");
            }

            var magicBytes = BitConverter.ToUInt64(bytes, 0);
            var byteOffset = sizeof(ulong);

            if (magicBytes != kMagicBytes)
            {
                throw new ArgumentException($"Serialized Image Tracking Library at '{libraryPath}' is not a valid image database file.");
            }

            for (int i = 0; i < serializedLibrary.count; ++i)
            {
                var referenceImage = serializedLibrary[i];
                var imageHandle    = MagicLeapImageTrackingSubsystem.Native.InvalidHandle;

                var widthInPixels = BitConverter.ToInt32(bytes, byteOffset);
                byteOffset += sizeof(int);
                var heightInPixels = BitConverter.ToInt32(bytes, byteOffset);
                byteOffset += sizeof(int);

                // Retain in case we destroy before the images have been processed
                RcoApi.Retain(m_NativePtr);
                RcoApi.Retain(m_NativeProviderPtr);
                fixed(byte *texturePtr = &bytes[byteOffset])
                {
                    var grayscaleImage = new NativeArray <byte>(widthInPixels * heightInPixels, Allocator.Persistent);

                    NativeArray <byte> .Copy(bytes, byteOffset, grayscaleImage, 0, widthInPixels *heightInPixels);

                    new AddImageJob
                    {
                        nativeProvider        = m_NativeProviderPtr,
                        database              = m_NativePtr,
                        managedReferenceImage = new ManagedReferenceImage(referenceImage),
                        grayscaleImage        = grayscaleImage,
                        width  = widthInPixels,
                        height = heightInPixels,
                        name   = new NativeArray <byte>(Encoding.UTF8.GetBytes(referenceImage.name + "\0"), Allocator.Persistent)
                    }.Schedule(m_CreateAssociatedNativeTrackerJobHandle);
                }

                byteOffset += widthInPixels * heightInPixels;
            }
        }
Beispiel #9
0
        /// <summary>
        /// Associate binary data with a string key.
        /// </summary>
        /// <remarks>
        /// Providers use this to associate provider-specific data with the library. During Player Build (in an
        /// [IPreprocessBuildWithReport.OnPreprocessBuild](xref:UnityEditor.Build.IPreprocessBuildWithReport.OnPreprocessBuild(UnityEditor.Build.Reporting.BuildReport))
        /// callback), the data store is first cleared. Each enabled provider then has an opportunity to add one or more
        /// entries for itself.
        ///
        /// Providers can use this to store a serialized version of the image library specific to that provider.
        /// Retrieve data with <see cref="UnityEngine.XR.ARSubsystems.XRReferenceImageLibrary.dataStore"/>.
        /// </remarks>
        /// <param name="library">The <see cref="UnityEngine.XR.ARSubsystems.XRReferenceImageLibrary"/> being extended.</param>
        /// <param name="key">The key which can be used to later retrieve <paramref name="data"/>.</param>
        /// <param name="data">The data to associate with <paramref name="key"/>.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="key"/> is `null`.</exception>
        public static void SetDataForKey(this XRReferenceImageLibrary library, string key, byte[] data)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            library.InternalSetDataForKey(key, data);
        }
Beispiel #10
0
        /// <summary>
        /// Sets the <c>XRReferenceImage.name</c> value on the <c><c>XRReferenceImage</c> at <paramref name="index"/>.
        /// This value is read-only in the Player; it can only be modified in the Editor.
        /// </summary>
        /// <param name="library">The <c>XRReferenceImageLibrary</c> being extended.</param>
        /// <param name="index">The index of the reference image within the library to modify.</param>
        /// <param name="name"></param>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="library"/> is <c>null</c>.</exception>
        /// <exception cref="System.IndexOutOfRangeException">Thrown if <paramref name="index"/> is not between 0 and <paramref name="library"/><c>.count - 1</c>.</exception>
        public static void SetName(this XRReferenceImageLibrary library, int index, string name)
        {
            ValidateAndThrow(library, index);

            var image = library.m_Images[index];

            image.m_Name            = name;
            library.m_Images[index] = image;
        }
Beispiel #11
0
            /// <summary>
            /// Creates a <c>RuntimeReferenceImageLibrary</c> from the passed in <c>XRReferenceImageLibrary</c> passed in.
            /// </summary>
            /// <param name="serializedLibrary">The <c>XRReferenceImageLibrary</c> that is used to create the <c>RuntimeReferenceImageLibrary</c></param>
            /// <returns>A new <c>RuntimeReferenceImageLibrary</c> created from the old  </returns>
            public override RuntimeReferenceImageLibrary CreateRuntimeLibrary(XRReferenceImageLibrary serializedLibrary)
            {
                if (s_NativeProviderPtr == IntPtr.Zero || s_NativeTrackerCreationJobHandle.Equals(default(JobHandle)))
                {
                    return(null);
                }

                return(new MagicLeapImageDatabase(serializedLibrary, s_NativeProviderPtr, s_NativeTrackerCreationJobHandle));
            }
Beispiel #12
0
        /// <summary>
        /// Sets the <c>XRReferenceImage.specifySize</c> value on the <c><c>XRReferenceImage</c> at <paramref name="index"/>.
        /// This value is read-only in the Player; it can only be modified in the Editor.
        /// </summary>
        /// <param name="library">The <c>XRReferenceImageLibrary</c> being extended.</param>
        /// <param name="index">The index of the reference image within the library to modify.</param>
        /// <param name="specifySize">Whether <c>XRReferenceImage.size</c> is specified.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="library"/> is <c>null</c>.</exception>
        /// <exception cref="System.IndexOutOfRangeException">Thrown if <paramref name="index"/> is not between 0 and <paramref name="library"/><c>.count - 1</c>.</exception>
        public static void SetSpecifySize(this XRReferenceImageLibrary library, int index, bool specifySize)
        {
            ValidateAndThrow(library, index);

            var image = library.m_Images[index];

            image.m_SpecifySize     = specifySize;
            library.m_Images[index] = image;
        }
Beispiel #13
0
        /// <summary>
        /// Sets the <c>XRReferenceImage.size</c> value on the <c><c>XRReferenceImage</c> at <paramref name="index"/>.
        /// This value is read-only in the Player; it can only be modified in the Editor.
        /// </summary>
        /// <param name="library">The <c>XRReferenceImageLibrary</c> being extended.</param>
        /// <param name="index">The index of the reference image within the library to modify.</param>
        /// <param name="size"></param>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="library"/> is <c>null</c>.</exception>
        /// <exception cref="System.IndexOutOfRangeException">Thrown if <paramref name="index"/> is not between 0 and <paramref name="library"/><c>.count - 1</c>.</exception>
        public static void SetSize(this XRReferenceImageLibrary library, int index, Vector2 size)
        {
            ValidateAndThrow(library, index);

            var image = library.m_Images[index];

            image.m_Size            = size;
            library.m_Images[index] = image;
        }
        static XRReferenceImage AddRefImageFromMarker(XRReferenceImageLibrary xrReferenceImageLibrary,
                                                      MarsMarkerDefinition marsMarkerDefinition)
        {
            xrReferenceImageLibrary.Add();
            // Just added entry is last
            var index = xrReferenceImageLibrary.count - 1;

            UpdateRefImage(xrReferenceImageLibrary, index, marsMarkerDefinition);
            return(xrReferenceImageLibrary[index]);
        }
Beispiel #15
0
        /// <summary>
        /// Set the texture on the reference image.
        /// </summary>
        /// <param name="library">The <see cref="XRReferenceImageLibrary"/> being extended.</param>
        /// <param name="index">The reference image index to modify.</param>
        /// <param name="texture">The texture to set.</param>
        /// <param name="keepTexture">Whether to store a strong reference to the texture. If <c>true</c>,
        /// the texture will be available in the Player. Otherwise, <c>XRReferenceImage.texture</c> will be set to <c>null</c>.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="library"/> is <c>null</c>.</exception>
        /// <exception cref="System.IndexOutOfRangeException">Thrown if <paramref name="index"/> is not between 0 and <paramref name="library"/><c>.count - 1</c>.</exception>
        public static void SetTexture(this XRReferenceImageLibrary library, int index, Texture2D texture, bool keepTexture)
        {
            ValidateAndThrow(library, index);

            var referenceImage = library.m_Images[index];

            referenceImage.m_SerializedTextureGuid = SerializableGuidUtil.Create(GetGuidForTexture(texture));
            referenceImage.m_Texture = keepTexture ? texture : null;
            library.m_Images[index]  = referenceImage;
        }
        /// <summary>
        /// Creates a <c>UnityEngine.XR.ARSubsystems.RuntimeReferenceImageLibrary</c> from an existing
        /// <c>UnityEngine.XR.ARSubsystems.XRReferenceImageLibrary</c>
        /// or an empty library if <paramref name="serializedLibrary"/> is <c>null</c>.
        /// Use this to construct reference image libraries at runtime. If the library is of type
        /// <c>MutableRuntimeReferenceImageLibrary</c>, it is modifiable at runtime.
        /// </summary>
        /// <param name="serializedLibrary">An existing <c>XRReferenceImageLibrary</c>, or <c>null</c> to create an empty mutable image library.</param>
        /// <returns>A new <c>RuntimeReferenceImageLibrary</c> representing the deserialized version of <paramref name="serializedLibrary"/>or an empty library if <paramref name="serializedLibrary"/> is <c>null</c>.</returns>
        /// <exception cref="System.NotSupportedException">Thrown if there is no subsystem. This usually means image tracking is not supported.</exception>
        public RuntimeReferenceImageLibrary CreateRuntimeLibrary(XRReferenceImageLibrary serializedLibrary = null)
        {
            CreateSubsystemIfNecessary();

            if (subsystem == null)
            {
                throw new NotSupportedException("No image tracking subsystem found. This usually means image tracking is not supported.");
            }

            return(subsystem.CreateRuntimeLibrary(serializedLibrary));
        }
Beispiel #17
0
        public static NativeArray <ManagedReferenceImage> ToNativeArray(this XRReferenceImageLibrary library, Allocator allocator)
        {
            var managedReferenceImages = new NativeArray <ManagedReferenceImage>(library.count, allocator);

            for (var i = 0; i < library.count; ++i)
            {
                managedReferenceImages[i] = new ManagedReferenceImage(library[i]);
            }

            return(managedReferenceImages);
        }
Beispiel #18
0
        /// <summary>
        /// Creates an empty <c>XRReferenceImage<c/> and adds it to the library. The new
        /// reference image is inserted at the end of the list of reference images.
        /// </summary>
        /// <param name="library">The <see cref="XRReferenceImageLibrary"/> being extended.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="library"/> is <c>null</c>.</exception>
        public static void Add(this XRReferenceImageLibrary library)
        {
            if (library == null)
            {
                throw new ArgumentNullException("library");
            }

            library.m_Images.Add(new XRReferenceImage
            {
                m_SerializedGuid = SerializableGuidUtil.Create(Guid.NewGuid())
            });
        }
    private unsafe void ChangeARCoreImagesDatabase(XRReferenceImageLibrary library, byte[] arcoreDB)
    {
        Debug.Log("Initializing DB Creation");
        if (arcoreDB == null || arcoreDB.Length == 0)
        {
            throw new InvalidOperationException(string.Format("Failed to load image library '{0}' - file was empty!", library.name));
        }
        var guids = new NativeArray <Guid>(library.count, Allocator.Temp);

        try
        {
            for (int i = 0; i < library.count; ++i)
                guids[i] = library[i].guid;

            fixed(byte *blob = arcoreDB)
            {
                // Retrieve the ARCore image tracking provider by reflection
                var provider = typeof(ARCoreImageTrackingProvider).GetNestedType("Provider", BindingFlags.NonPublic | BindingFlags.Instance);

                Debug.Log("retrieved image tracking provider");

                // Destroy the current image tracking database
                var destroy = provider.GetMethod("UnityARCore_imageTracking_destroy", BindingFlags.NonPublic | BindingFlags.Static);

                destroy.Invoke(null, null);
                Debug.Log("Destroyed current tracking database");

                // Set the image tracking database
                var setDatabase = provider.GetMethod("UnityARCore_imageTracking_setDatabase", BindingFlags.NonPublic | BindingFlags.Static);

                setDatabase.Invoke(null, new object[]
                {
                    new IntPtr(blob),
                    arcoreDB.Length,
                    new IntPtr(guids.GetUnsafePtr()),
                    guids.Length
                });
                Debug.Log("Database creation completed");
            }
        }
        catch (Exception e)
        {
            Debug.LogError(string.Format("Error while loading '{0}': {1}", library.name, e));
        }
        finally
        {
            guids.Dispose();
        }

//		foreach (var referenceImage in library)
//			Debug.LogFormat("Image guid: {0}", referenceImage.guid);
    }
        static string ToInputImageListPath(this XRReferenceImageLibrary library, string destinationDirectory)
        {
            var entries = new List <string>();

            foreach (var referenceImage in library)
            {
                entries.Add(referenceImage.ToImgDBEntry(destinationDirectory));
            }

            var path = Path.Combine(destinationDirectory, $"{GetTempFileNameWithoutExtension()}.txt");

            File.WriteAllText(path, string.Join("\n", entries));

            return(path);
        }
Beispiel #21
0
        public MagicLeapImageDatabase(XRReferenceImageLibrary serializedLibrary, IntPtr nativeProviderHandle, JobHandle imageTrackerCreationJobHandle)
        {
            m_NativeProviderPtr = nativeProviderHandle;
            m_CreateAssociatedNativeTrackerJobHandle = imageTrackerCreationJobHandle;
            m_NativePtr = Construct();

            if (m_NativePtr == IntPtr.Zero)
            {
                throw new InvalidOperationException($"Native Library for {serializedLibrary.name} failed to construct.");
            }

            if (serializedLibrary != null && serializedLibrary.count > 0)
            {
                DeserializeImageDatabaseFile(serializedLibrary);
            }
        }
Beispiel #22
0
        static void ValidateAndThrow(XRReferenceImageLibrary library, int index)
        {
            if (library == null)
            {
                throw new ArgumentNullException("library");
            }

            if (library.count == 0)
            {
                throw new IndexOutOfRangeException("The reference image library is empty; cannot index into it.");
            }

            if (index < 0 || index >= library.count)
            {
                throw new IndexOutOfRangeException(string.Format("{0} is out of range. 'index' must be between 0 and {1}", index, library.count - 1));
            }
        }
        static AssetDeleteResult HandleAssetDelete(XRReferenceImageLibrary xrLibrary)
        {
            if (MarkerProviderSettings.instance.TryFind(xrLibrary, out var marsLibrary))
            {
                Debug.LogWarning($"You must delete the MarsMarkerLibrary {marsLibrary} before deleting its associated XRReferenceImageLibrary", marsLibrary);

                // Return DidDelete to prevent deleting the asset in this case
                return(AssetDeleteResult.DidDelete);
            }

            if (k_DeletedLibraries.Remove(xrLibrary))
            {
                return(AssetDeleteResult.DidDelete);
            }

            return(AssetDeleteResult.DidNotDelete);
        }
        public static NSString GetARResourceGroupName(this XRReferenceImageLibrary library)
        {
            if (library.dataStore.TryGetValue(ARKitPackageInfo.identifier, out var data))
            {
                return(new NSString(ARKitImageDatabase.resourceGroupName));
            }

            // Otherwise, construct the name based on the library's name + guid
            var name = new NSMutableString(library.name);

            name.Append(NSString.underscore);
            using (var uuid = library.guid.ToNSString())
            {
                name.Append(uuid);
            }

            return(name);
        }
        public unsafe ARCoreImageDatabase(XRReferenceImageLibrary serializedLibrary)
        {
            if (serializedLibrary == null)
            {
                m_NativePtr = UnityARCore_ImageDatabase_deserialize(default(NativeView <byte>), default(NativeView <ManagedReferenceImage>));
            }
            else
            {
                using (var webRequest = new UnityWebRequest(ARCoreImageTrackingProvider.GetPathForLibrary(serializedLibrary)))
                {
                    webRequest.downloadHandler = new DownloadHandlerBuffer();
                    webRequest.disposeDownloadHandlerOnDispose = true;
                    webRequest.SendWebRequest();
                    while (!webRequest.isDone)
                    {
                    }

                    byte[] libraryBlob = webRequest.downloadHandler.data;
                    if (libraryBlob == null || libraryBlob.Length == 0)
                    {
                        throw new InvalidOperationException(string.Format(
                                                                "Failed to load image library '{0}' - file was empty!", serializedLibrary.name));
                    }

                    var managedReferenceImages = new NativeArray <ManagedReferenceImage>(serializedLibrary.count, Allocator.Temp);
                    try
                    {
                        for (int i = 0; i < serializedLibrary.count; ++i)
                        {
                            managedReferenceImages[i] = new ManagedReferenceImage(serializedLibrary[i]);
                        }

                        fixed(byte *blob = libraryBlob)
                        {
                            m_NativePtr = UnityARCore_ImageDatabase_deserialize(new NativeView <byte>(blob, libraryBlob.Length), managedReferenceImages);
                        }
                    }
                    finally
                    {
                        managedReferenceImages.Dispose();
                    }
                }
            }
        }
 void OnEnable()
 {
     if (!EditorApplication.isPlayingOrWillChangePlaymode)
     {
         referenceImageLibrary = serializedObject.FindProperty("referenceImageLibrary");
         if (referenceImageLibrary.objectReferenceValue != null)
         {
             library   = referenceImageLibrary.objectReferenceValue as XRReferenceImageLibrary;
             drawIndex = new int[library.count];
         }
         possibleHandlerNames = GetAllHandlerNames();
         possibleHandlerNames.Insert(0, "None");
         lookupInfo = serializedObject.FindProperty("handlerInfoList");
         if (library != null)
         {
             GetLookUpList();
         }
     }
 }
        /// <summary>
        /// Sets the image library on the subsystem before Start() is called on the <c>XRImageTrackingSubsystem</c>.
        /// </summary>
        protected override void OnBeforeStart()
        {
            if (subsystem.imageLibrary == null && m_SerializedLibrary != null)
            {
                subsystem.imageLibrary = subsystem.CreateRuntimeLibrary(m_SerializedLibrary);
                m_SerializedLibrary    = null;
            }

            UpdateReferenceImages(subsystem.imageLibrary);
            SetMaxNumberOfMovingImages(m_MaxNumberOfMovingImages);

            enabled = (subsystem.imageLibrary != null);
#if DEVELOPMENT_BUILD
            if (subsystem.imageLibrary == null)
            {
                Debug.LogWarning($"{nameof(ARTrackedImageManager)} '{name}' was enabled but no reference image library is specified. To enable, set a valid reference image library and then re-enable this component.");
            }
#endif
        }
Beispiel #28
0
        static byte[] GetLibraryData(XRReferenceImageLibrary library)
        {
            // 4.2+
            if (library.dataStore.TryGetValue(dataStoreKey, out var bytes))
            {
                return(bytes);
            }

            // Pre 4.2 fallback
            using var webRequest = new UnityWebRequest(ARCoreImageTrackingSubsystem.GetPathForLibrary(library))
                  {
                      downloadHandler = new DownloadHandlerBuffer(),
                      disposeDownloadHandlerOnDispose = true
                  };

            webRequest.SendWebRequest();
            while (!webRequest.isDone)
            {
            }

            return(webRequest.downloadHandler.data);
        }
Beispiel #29
0
        public unsafe ARKitImageDatabase(XRReferenceImageLibrary serializedLibrary)
        {
            if (serializedLibrary == null)
            {
                nativePtr = UnityARKit_ImageDatabase_createEmpty();
            }
            else
            {
                var managedReferenceImages = new NativeArray <ManagedReferenceImage>(serializedLibrary.count, Allocator.Temp);
                for (int i = 0; i < serializedLibrary.count; ++i)
                {
                    managedReferenceImages[i] = new ManagedReferenceImage(serializedLibrary[i]);
                }

                using (managedReferenceImages)
                {
                    var nativeReturnCode = UnityARKit_ImageDatabase_tryCreateFromResourceGroup(
                        serializedLibrary.name, serializedLibrary.name.Length, serializedLibrary.guid,
                        managedReferenceImages.GetUnsafePtr(), managedReferenceImages.Length,
                        out IntPtr ptr);

                    switch (nativeReturnCode)
                    {
                    case SetReferenceLibraryResult.Success:
                        nativePtr = ptr;
                        break;

                    case SetReferenceLibraryResult.FeatureUnavailable:
                        throw new InvalidOperationException($"Failed to resolve image library '{serializedLibrary.name}'. This feature only works on versions of ARKit 11.3 and newer.");

                    case SetReferenceLibraryResult.ResourceDoesNotExist:
                        throw new InvalidOperationException($"Failed to resolve image library '{serializedLibrary.name}'. There is no matching resource group, or the resource group does not contain any reference images.");

                    default:
                        throw new InvalidOperationException($"Unexpected return code {nativeReturnCode} encountered while trying to create a reference image library with name {serializedLibrary.name}.");
                    }
                }
            }
        }
Beispiel #30
0
 public unsafe override RuntimeReferenceImageLibrary CreateRuntimeLibrary(
     XRReferenceImageLibrary serializedLibrary)
 {
     return(new ARKitImageDatabase(serializedLibrary));
 }