Example #1
0
 public void UpdateCameraPose(Camera arCamera,
                              QCARManager.TrackableData[] trackableDataArray,
                              int originTrackableID)
 {
     // If there is a World Center Trackable use it to position the camera.
     if (originTrackableID >= 0)
     {
         foreach (QCARManager.TrackableData trackableData in trackableDataArray)
         {
             if (trackableData.id == originTrackableID)
             {
                 if (trackableData.status ==
                     TrackableBehaviour.Status.DETECTED ||
                     trackableData.status ==
                     TrackableBehaviour.Status.TRACKED)
                 {
                     MarkerBehaviour originTrackable = null;
                     if (TryGetMarkerByID(originTrackableID,
                                          out originTrackable))
                     {
                         if (originTrackable.enabled)
                         {
                             PositionCamera(originTrackable, arCamera,
                                            trackableData.pose);
                         }
                     }
                 }
                 break;
             }
         }
     }
 }
Example #2
0
    protected override void CheckIfDetectedMarkers()
    {
        base.CheckIfDetectedMarkers();

        for (int i = 0; i < ids.Length; i++)
        {
            Cv2.CornerSubPix(grayedImg, corners[i], new Size(5, 5), new Size(-1, -1), TermCriteria.Both(30, 0.1));

            if (!MarkerManager.IsMarkerRegistered(ids[i]))
            {
                continue;
            }

            MarkerBehaviour m = MarkerManager.GetMarker(ids[i]);

            if (!allDetectedMarkers.ContainsKey(ids[i]))
            {
                m.OnMarkerDetected.Invoke();
                allDetectedMarkers.Add(m.GetMarkerID(), m);
            }

            // m.UpdateMarker(img.Cols, img.Rows, corners[i], rejectedImgPoints[i]);
            m.UpdateMarker(corners[i], calibrationData.GetCameraMatrix(),
                           calibrationData.GetDistortionCoefficients(), grayedImg);
        }
    }
Example #3
0
    // Creates a marker with the given id, name, and size.
    // Registers the marker at native code.
    // Returns a MarkerBehaviour object to receive updates.
    public MarkerBehaviour CreateMarker(int markerID, String trackableName, float size)
    {
        int trackableID = RegisterMarker(markerID, trackableName, size);

        if (trackableID == -1)
        {
            Debug.LogError("Could not create marker with id " + markerID + ".");
            return(null);
        }

        // Alternatively instantiate Trackable Prefabs.
        GameObject      markerObject = new GameObject();
        MarkerBehaviour newMB        =
            markerObject.AddComponent <MarkerBehaviour>();

        Debug.Log("Creating Marker with values: " +
                  "\n MarkerID:     " + markerID +
                  "\n TrackableID:  " + trackableID +
                  "\n Name:         " + trackableName +
                  "\n Size:         " + size + "x" + size);

        newMB.InitializeID(trackableID);
        newMB.MarkerID             = markerID;
        newMB.TrackableName        = trackableName;
        newMB.transform.localScale = new Vector3(size, size, size);

        // Add newly created Marker to dictionary.
        mMarkerBehaviourDict[trackableID] = newMB;

        return(newMB);
    }
Example #4
0
    // Updates the scale values in the transform component from a given size.
    public static void UpdateScale(MarkerBehaviour marker, Vector2 size)
    {
        // Update the scale.
        float childScaleFactor = marker.GetSize()[0] / size[0];

        marker.transform.localScale = new Vector3(size[0], size[0], size[0]);

        // Check if 3D content should keep its size or if it should be scaled
        // with the target.
        if (marker.mPreserveChildSize)
        {
            foreach (Transform child in marker.transform)
            {
                child.localPosition =
                    new Vector3(child.localPosition.x * childScaleFactor,
                                child.localPosition.y * childScaleFactor,
                                child.localPosition.z * childScaleFactor);

                child.localScale =
                    new Vector3(child.localScale.x * childScaleFactor,
                                child.localScale.y * childScaleFactor,
                                child.localScale.z * childScaleFactor);
            }
        }
    }
Example #5
0
    private void OnTrackingFound()
    {
        Renderer[] rendererComponents = GetComponentsInChildren <Renderer>(true);
        Collider[] colliderComponents = GetComponentsInChildren <Collider>(true);

        // Enable rendering:
        foreach (Renderer component in rendererComponents)
        {
            component.enabled = true;
        }

        // Enable colliders:
        foreach (Collider component in colliderComponents)
        {
            component.enabled = true;
        }

        Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " found");

        MarkerBehaviour markerBehaviour = GetComponent <MarkerBehaviour>();

        if (markerBehaviour)
        {
            MonAgent.SetLastFoundMonID(markerBehaviour.Marker.MarkerID);
            StateAgent.ChangeState(StateAgent.State.Playing);
        }
    }
Example #6
0
    // Updates the scale values in the transform component from a given size.
    public static void UpdateScale(MarkerBehaviour marker, Vector2 size)
    {
        // Update the scale.
        float childScaleFactor = marker.GetSize()[0] / size[0];

        marker.transform.localScale = new Vector3(size[0], size[0], size[0]);

        // Check if 3D content should keep its size or if it should be scaled
        // with the target.
        if (marker.mPreserveChildSize)
        {
            foreach (Transform child in marker.transform)
            {
                child.localPosition =
                    new Vector3(child.localPosition.x * childScaleFactor,
                                child.localPosition.y * childScaleFactor,
                                child.localPosition.z * childScaleFactor);

                child.localScale =
                    new Vector3(child.localScale.x * childScaleFactor,
                                child.localScale.y * childScaleFactor,
                                child.localScale.z * childScaleFactor);
            }
        }
    }
    void Start()
    {
        if (game == null) {
          game = Camera.main.GetComponent<Game>();
        }

        markerBehaviour = GetComponent<MarkerBehaviour>();
    }
Example #8
0
    protected override void CheckIfDetectedMarkers()
    {
        base.CheckIfDetectedMarkers();

        for (int i = 0; i < ids.Length; i++)
        {
            Cv2.CornerSubPix(grayedImg, corners[i], new Size(5, 5), new Size(-1, -1), TermCriteria.Both(30, 0.1));

            if (!MarkerManager.IsMarkerRegistered(ids[i]))
            {
                continue;
            }

            MarkerBehaviour m = MarkerManager.GetMarker(ids[i]);

            if (!allDetectedMarkers.ContainsKey(ids[i]))
            {
                Debug.Log("FOUND MARKER: " + m.GetMarkerID());
                m.OnMarkerDetected.Invoke();
                allDetectedMarkers.Add(m.GetMarkerID(), m);
            }

            float rotZ = 0;

            switch (Screen.orientation)
            {
            case ScreenOrientation.Portrait:
                rotZ = 90;
                break;

            case ScreenOrientation.LandscapeLeft:
                rotZ = 180;
                break;

            case ScreenOrientation.LandscapeRight:
                rotZ = 0;
                break;

            case ScreenOrientation.PortraitUpsideDown:
                rotZ = -90;
                break;
            }

            if (!UseCustomCalibration)
            {
                cameraManager.TryGetIntrinsics(out cameraIntrinsics);

                m.UpdateMarker(corners[i], cameraIntrinsics, grayedImg, Vector3.forward * rotZ);
            }
            else
            {
                m.UpdateMarker(corners[i], calibrationData.GetCameraMatrix(), calibrationData.GetDistortionCoefficients(), grayedImg, Vector3.forward * rotZ);
            }
        }
    }
    //Calculates the target pose for the camera in order to appear in front of the marker.
    private Pose GetTargetPose(MarkerBehaviour marker)
    {
        Matrix4x4 m          = marker.GetMatrix();
        Matrix4x4 inverseMat = m.inverse;
        Pose      p          = new Pose();

        p.rotation  = ARucoUnityHelper.GetQuaternion(inverseMat);
        p.position  = marker.transform.position;
        p.position += ARucoUnityHelper.GetPosition(inverseMat);

        return(p);
    }
    private static void CheckMesh(MarkerBehaviour mb)
    {
        // when copy-pasting targets between scenes, the mesh and materials of
        // the game objects get lost. This checks for them and re-creates them if they are found missing.
        GameObject mbObject = mb.gameObject;

        MeshFilter meshFilter = mbObject.GetComponent <MeshFilter>();

        if (meshFilter == null || meshFilter.sharedMesh == null)
        {
            CreateMesh(mb);
        }
    }
Example #11
0
    // Create a mesh with size 1, 1.
    public static void CreateMesh(MarkerBehaviour marker)
    {
        GameObject markerObject = marker.gameObject;

        MeshFilter meshFilter = markerObject.GetComponent <MeshFilter>();

        if (!meshFilter)
        {
            meshFilter = markerObject.AddComponent <MeshFilter>();
        }

        // Setup vertex positions.
        Vector3 p0 = new Vector3(-0.5f, 0, -0.5f);
        Vector3 p1 = new Vector3(-0.5f, 0, 0.5f);
        Vector3 p2 = new Vector3(0.5f, 0, -0.5f);
        Vector3 p3 = new Vector3(0.5f, 0, 0.5f);

        Mesh mesh = new Mesh();

        mesh.vertices  = new Vector3[] { p0, p1, p2, p3 };
        mesh.triangles = new int[]  {
            0, 1, 2,
            2, 1, 3
        };

        // Add UV coordinates.
        mesh.uv = new Vector2[] {
            new Vector2(0, 0),
            new Vector2(0, 1),
            new Vector2(1, 0),
            new Vector2(1, 1)
        };

        // Add empty normals array.
        mesh.normals = new Vector3[mesh.vertices.Length];

        // Automatically calculate normals.
        mesh.RecalculateNormals();
        meshFilter.mesh = mesh;

        MeshRenderer meshRenderer = markerObject.GetComponent <MeshRenderer>();

        if (!meshRenderer)
        {
            meshRenderer = markerObject.AddComponent <MeshRenderer>();
        }

        // Cleanup assets that have been created temporarily.
        EditorUtility.UnloadUnusedAssets();
    }
    //Calculates the matrix needed to place the camera in front of the marker.
    private Matrix4x4 GetPoseMatrix(MarkerBehaviour marker)
    {
        Pose targetPose = GetTargetPose(marker);

        currentTrackedMarkerTransform.SetPositionAndRotation(targetPose.position, targetPose.rotation);

        Matrix4x4 camMat = Matrix4x4.TRS(arCamera.transform.localPosition, arCamera.transform.localRotation,
                                         arCamera.transform.localScale);

        Matrix4x4 newHolder =
            currentTrackedMarkerTransform.localToWorldMatrix * camMat.inverse;

        return(newHolder);
    }
Example #13
0
    private void InitializeMarkerBehaviour(MarkerBehaviour markerBehaviour, Marker marker)
    {
        IEditorMarkerBehaviour editorMarkerBehaviour = markerBehaviour;

        editorMarkerBehaviour.InitializeMarker(marker);
        if (!mTrackableBehaviours.ContainsKey(marker.ID))
        {
            // Add MarkerBehaviour to dictionary.
            mTrackableBehaviours[marker.ID] = markerBehaviour;

            Debug.Log("Found Marker named " + marker.Name +
                      " with id " + marker.ID);
        }
    }
    // Lets the user choose a Marker by specifying an ID.
    public override void OnInspectorGUI()
    {
        EditorGUIUtility.LookLikeInspector();

        DrawDefaultInspector();

        MarkerBehaviour        mb       = (MarkerBehaviour)target;
        IEditorMarkerBehaviour editorMb = mb;

        if (QCARUtilities.GetPrefabType(mb) == PrefabType.Prefab)
        {
            // Only allow initial values for prefabs.
            editorMb.SetMarkerID(-1);
            EditorGUILayout.IntField("Marker ID", editorMb.MarkerID);
            EditorGUILayout.Toggle("Preserve child size",
                                   editorMb.PreserveChildSize);
        }
        else
        {
            int newMarkerID = EditorGUILayout.IntField("Marker ID",
                                                       editorMb.MarkerID);

            if (newMarkerID < 0)
            {
                newMarkerID = 0;
            }
            else if (newMarkerID >=
                     QCARUtilities.GlobalVars.MAX_NUM_FRAME_MARKERS)
            {
                newMarkerID =
                    QCARUtilities.GlobalVars.MAX_NUM_FRAME_MARKERS - 1;
            }

            if (newMarkerID != editorMb.MarkerID)
            {
                editorMb.SetMarkerID(newMarkerID);
                editorMb.SetNameForTrackable("FrameMarker" + newMarkerID);
            }

            editorMb.SetPreserveChildSize(EditorGUILayout.Toggle("Preserve child size",
                                                                 editorMb.PreserveChildSize));
        }

        if (GUI.changed)
        {
            EditorUtility.SetDirty(mb);

            SceneManager.Instance.SceneUpdated();
        }
    }
        /// <summary>
        /// Removes the marker.
        /// </summary>
        /// <param name='m'>
        /// The marker.
        /// </param>
        /// <exception cref='ArgumentNullException'>
        /// Is thrown when an argument passed to a method is invalid because it is <see langword="null" /> .
        /// </exception>
        /// <exception cref='ArgumentOutOfRangeException'>
        /// Is thrown when an argument passed to a method is invalid because it is outside the allowable range of values as
        /// specified by the method.
        /// </exception>
        public void RemoveMarker(MarkerBehaviour m)
        {
            if (m == null)
            {
                throw new ArgumentNullException("m");
            }

            if (markers.Contains(m) == false)
            {
                throw new ArgumentOutOfRangeException("m");
            }

            markers.Remove(m);

            DestroyImmediate(m.gameObject);
        }
Example #16
0
    // Lets the user choose a Marker by specifying an ID.
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        MarkerBehaviour mb = (MarkerBehaviour)target;

        if (QCARUtilities.GetPrefabType(mb) == PrefabType.Prefab)
        {
            // Only allow initial values for prefabs.
            mb.MarkerID = -1;
            EditorGUILayout.IntField("Marker ID", mb.MarkerID);
            EditorGUILayout.Toggle("Preserve child size",
                                   mb.mPreserveChildSize);
        }
        else
        {
            int newMarkerID = EditorGUILayout.IntField("Marker ID",
                                                       mb.MarkerID);

            if (newMarkerID < 0)
            {
                newMarkerID = 0;
            }
            else if (newMarkerID >=
                     QCARUtilities.GlobalVars.MAX_NUM_FRAME_MARKERS)
            {
                newMarkerID =
                    QCARUtilities.GlobalVars.MAX_NUM_FRAME_MARKERS - 1;
            }

            if (newMarkerID != mb.MarkerID)
            {
                mb.MarkerID = newMarkerID;
            }

            mb.mPreserveChildSize =
                EditorGUILayout.Toggle("Preserve child size",
                                       mb.mPreserveChildSize);
        }

        if (GUI.changed)
        {
            EditorUtility.SetDirty(mb);

            SceneManager.Instance.SceneUpdated();
        }
    }
Example #17
0
    // Create a mesh with size 1, 1.
    public static void CreateMesh(MarkerBehaviour marker)
    {
        GameObject markerObject = marker.gameObject;

        MeshFilter meshFilter = markerObject.GetComponent<MeshFilter>();
        if (!meshFilter)
        {
            meshFilter = markerObject.AddComponent<MeshFilter>();
        }

        // Setup vertex positions.
        Vector3 p0 = new Vector3(-0.5f, 0, -0.5f);
        Vector3 p1 = new Vector3(-0.5f, 0, 0.5f);
        Vector3 p2 = new Vector3(0.5f, 0, -0.5f);
        Vector3 p3 = new Vector3(0.5f, 0, 0.5f);

        Mesh mesh = new Mesh();
        mesh.vertices = new Vector3[] { p0, p1, p2, p3 };
        mesh.triangles = new int[]  {
                                        0,1,2,
                                        2,1,3
                                    };

        // Add UV coordinates.
        mesh.uv = new Vector2[]{
                new Vector2(0,0),
                new Vector2(0,1),
                new Vector2(1,0),
                new Vector2(1,1)
                };

        // Add empty normals array.
        mesh.normals = new Vector3[mesh.vertices.Length];

        // Automatically calculate normals.
        mesh.RecalculateNormals();
        meshFilter.mesh = mesh;

        MeshRenderer meshRenderer = markerObject.GetComponent<MeshRenderer>();
        if (!meshRenderer)
        {
            meshRenderer = markerObject.AddComponent<MeshRenderer>();
        }

        // Cleanup assets that have been created temporarily.
        EditorUtility.UnloadUnusedAssets();
    }
    protected override void StopUpdatingCameraPose(int[] ids)
    {
        base.StopUpdatingCameraPose(ids);

        if (trackingTarget == null)
        {
            return;
        }

        //set the tracking target to null if its one of the lost ids.
        for (int i = 0; i < ids.Length; i++)
        {
            if (ids[i] == trackingTarget.GetMarkerID())
            {
                trackingTarget = null;
                return;
            }
        }
    }
    // Initializes the Marker when it is drag-dropped into the scene.
    public void OnEnable()
    {
        MarkerBehaviour markerBehaviour = (MarkerBehaviour)target;

        // We don't want to initialize if this is a prefab.
        if (QCARUtilities.GetPrefabType(markerBehaviour) == PrefabType.Prefab)
        {
            return;
        }

        // Initialize scene manager
        if (!SceneManager.Instance.SceneInitialized)
        {
            SceneManager.Instance.InitScene();
        }

        IEditorMarkerBehaviour editorMarkerBehaviour = markerBehaviour;

        // Only setup marker if it has not been set up previously.
        if (!editorMarkerBehaviour.InitializedInEditor && !EditorApplication.isPlaying)
        {
            editorMarkerBehaviour.SetMarkerID(SceneManager.Instance.GetNextFrameMarkerID());

            CreateMesh(markerBehaviour);
            editorMarkerBehaviour.SetNameForTrackable("FrameMarker" + editorMarkerBehaviour.MarkerID);
            markerBehaviour.name = "FrameMarker" + editorMarkerBehaviour.MarkerID;
            editorMarkerBehaviour.SetInitializedInEditor(true);

            // Inform Unity that the behaviour properties have changed.
            EditorUtility.SetDirty(markerBehaviour);

            // Inform the scene manager about the newly added marker (to get validation).
            SceneManager.Instance.SceneUpdated();
        }
        else if (!EditorApplication.isPlaying)
        {
            CheckMesh(markerBehaviour);
        }

        // Cache the current scale of the marker:
        editorMarkerBehaviour.SetPreviousScale(markerBehaviour.transform.localScale);
    }
Example #20
0
    // Destroys the marker associated with the given MarkerBehaviour
    // at native code.
    public bool DestroyMarker(MarkerBehaviour marker, bool destroyGameObject)
    {
        if (markerTrackerDestroyMarker(marker.TrackableID) == 0)
        {
            Debug.LogError("Could not destroy marker with id " + marker.MarkerID + ".");
            return(false);
        }

        mMarkerBehaviourDict.Remove(marker.TrackableID);

        if (destroyGameObject)
        {
            GameObject.Destroy(marker.gameObject);
        }

        // Tell QCARManager to reinitialize its trackable array.
        QCARManager.Instance.Reinit();

        return(true);
    }
Example #21
0
    // Returns the Marker at the given index.
    public MarkerBehaviour GetMarker(int index)
    {
        Dictionary <int, MarkerBehaviour> .Enumerator enumerator =
            mMarkerBehaviourDict.GetEnumerator();

        MarkerBehaviour mb = null;

        for (int i = 0; i <= index; ++i)
        {
            if (!enumerator.MoveNext())
            {
                Debug.LogError("Marker index invalid.");
                mb = null;
                break;
            }

            mb = enumerator.Current.Value;
        }

        return(mb);
    }
    // Creates a marker with the given id, name, and size.
    // Registers the marker at native code.
    // Returns a MarkerBehaviour object to receive updates.
    public override MarkerBehaviour CreateMarker(int markerID, String trackableName, float size)
    {
        int trackableID = RegisterMarker(markerID, trackableName, size);

        if (trackableID == -1)
        {
            Debug.LogError("Could not create marker with id " + markerID + ".");
            return(null);
        }

        // create a new marker object:
        Marker marker = new MarkerImpl(trackableName, trackableID, size, markerID);

        // Add newly created Marker to dictionary.
        mMarkerDict[trackableID] = marker;

        // let the state manager create a new Marker Behaviour and return it:
        StateManagerImpl stateManager = (StateManagerImpl)TrackerManager.Instance.GetStateManager();
        MarkerBehaviour  newMB        = stateManager.CreateNewMarkerBehaviourForMarker(marker, trackableName);

        return(newMB);
    }
    /// <summary>
    /// Takes a given GameObject to add a new MarkerBehaviour to. This new Behaviour is associated with the given Marker
    /// </summary>
    public MarkerBehaviour CreateNewMarkerBehaviourForMarker(Marker trackable, GameObject gameObject)
    {
        MarkerBehaviour newMB =
            gameObject.AddComponent <MarkerBehaviour>();

        float markerSize = trackable.GetSize();

        Debug.Log("Creating Marker with values: " +
                  "\n MarkerID:     " + trackable.MarkerID +
                  "\n TrackableID:  " + trackable.ID +
                  "\n Name:         " + trackable.Name +
                  "\n Size:         " + markerSize + "x" + markerSize);

        IEditorMarkerBehaviour newEditorMB = newMB;

        newEditorMB.SetMarkerID(trackable.MarkerID);
        newEditorMB.SetNameForTrackable(trackable.Name);
        newEditorMB.transform.localScale = new Vector3(markerSize, markerSize, markerSize);
        newEditorMB.InitializeMarker(trackable);

        return(newMB);
    }
Example #24
0
    public void DestroyAllMarkers(bool destroyGameObject)
    {
        int numMarkers = GetNumMarkers();

        for (int i = 0; i < numMarkers; i++)
        {
            MarkerBehaviour marker = GetMarker(i);
            if (markerTrackerDestroyMarker(marker.TrackableID) == 0)
            {
                Debug.LogError("Could not destroy marker with id " + marker.MarkerID + ".");
            }

            if (destroyGameObject)
            {
                GameObject.Destroy(marker.gameObject);
            }
        }

        mMarkerBehaviourDict.Clear();

        // Tell QCARManager to reinitialize its trackable array.
        QCARManager.Instance.Reinit();
    }
Example #25
0
    // Initializes the Marker when it is drag-dropped into the scene.
    public void OnEnable()
    {
        MarkerBehaviour markerBehaviour = (MarkerBehaviour)target;

        // We don't want to initialize if this is a prefab.
        if (QCARUtilities.GetPrefabType(markerBehaviour) == PrefabType.Prefab)
        {
            return;
        }

        // Initialize scene manager
        if (!SceneManager.Instance.SceneInitialized)
        {
            SceneManager.Instance.InitScene();
        }

        // Only setup marker if it has not been set up previously.
        if (!markerBehaviour.mInitializedInEditor)
        {
            markerBehaviour.MarkerID =
                SceneManager.Instance.GetNextFrameMarkerID();

            CreateMesh(markerBehaviour);
            markerBehaviour.TrackableName        = "FrameMarker" + markerBehaviour.MarkerID; // fmConfig.name;
            markerBehaviour.name                 = "FrameMarker" + markerBehaviour.MarkerID;
            markerBehaviour.mInitializedInEditor = true;

            // Inform Unity that the behaviour properties have changed.
            EditorUtility.SetDirty(markerBehaviour);

            // Inform the scene manager about the newly added marker (to get validation).
            SceneManager.Instance.SceneUpdated();
        }

        // Cache the current scale of the marker:
        markerBehaviour.mPreviousScale = markerBehaviour.transform.localScale;
    }
    protected override void ConcentrateOnTheClosestMarker(int[] markerIds)
    {
        MarkerBehaviour closestMarker   = null;
        float           closestDistance = Mathf.Infinity;

        markersCache.Clear();

        //Perform direction filtering
        if (minDirectionDotProductValue >= -0.9f)
        {
            Vector3    oldPos      = transform.position;
            Quaternion oldRotation = transform.rotation;

            foreach (int i in markerIds)
            {
                MarkerBehaviour m = MarkerManager.GetMarker(i);

                if (m == null)
                {
                    continue;
                }

                Pose targetPose = GetTargetPose(m);

                //Move in the target pose before checking for direction
                transform.SetPositionAndRotation(targetPose.position, targetPose.rotation);

                Vector3 cameraForward = new Vector3(transform.forward.x, 0, transform.forward.z);
                Vector3 markerForward = new Vector3(m.transform.forward.x, 0, m.transform.forward.z);

                float dot = Vector3.Dot(cameraForward, markerForward);

                // Debug.Log("DOT: " + dot);

                if (dot > 0)
                {
                    //store the ones that we need
                    markersCache.Add(m);
                }
                else
                {
                    if (trackingTarget != null && m.GetMarkerID() == trackingTarget.GetMarkerID())
                    {
                        trackingTarget = null;
                    }
                }
            }

            //move back where we were
            transform.SetPositionAndRotation(oldPos, oldRotation);
        }

        // if we didnt find anything just check for the closest one
        if (markersCache.Count == 0 || minDirectionDotProductValue < -0.9f)
        {
            foreach (int i in markerIds)
            {
                MarkerBehaviour m = MarkerManager.GetMarker(i);

                if (m == null)
                {
                    continue;
                }

                markersCache.Add(m);
            }
        }

        // go through the cache and check for the closest marker and make it the target marker
        foreach (MarkerBehaviour m in markersCache)
        {
            //Debug.Log("IDD: " + i);
            if (GetMarkerDistanceFromCamera(m) < closestDistance)
            {
                closestDistance = GetMarkerDistanceFromCamera(m);
                closestMarker   = m;
            }

            // Debug.Log("ID: " + i + " " + "Distance: " + GetMarkerDistanceFromCamera(m));
        }

        if (closestMarker == null)
        {
            return;
        }

        if (trackingTarget == null)
        {
            trackingTarget = closestMarker;
            Debug.Log("here");
            return;
        }

        float d1 = GetMarkerDistanceFromCamera(closestMarker);
        float d2 = GetMarkerDistanceFromCamera(trackingTarget);

        float difference = Mathf.Abs(d1 - d2);

        //Debug.Log(difference);
        if (difference > 0.1)
        {
            trackingTarget = closestMarker;
        }
    }
Example #27
0
    public void AddMarkers(MarkerBehaviour[] markerBehaviours)
    {
        foreach (MarkerBehaviour marker in markerBehaviours)
        {
            if (marker.TrackableName == null)
            {
                Debug.LogError("Found Marker without name.");
                continue;
            }

            int id = RegisterMarker(marker.MarkerID, marker.TrackableName, marker.GetSize().x);

            if (id == -1)
            {
                Debug.LogWarning("Marker named " + marker.TrackableName +
                                 " could not be registered, disabling.");
                marker.enabled = false;
            }
            else
            {
                marker.InitializeID(id);
                if (!mMarkerBehaviourDict.ContainsKey(id))
                {
                    mMarkerBehaviourDict[id] = marker;
                    Debug.Log("Found Marker named " + marker.TrackableName +
                                " with id " + marker.TrackableID);
                }
                marker.enabled = true;
            }
        }
    }
Example #28
0
 protected float GetMarkerDistanceFromCamera(MarkerBehaviour m)
 {
     return(ARucoUnityHelper.GetPosition(m.GetMatrix()).magnitude);
 }
Example #29
0
 // The one MarkerBehaviour instance this accessor belongs to is set in the
 // constructor.
 public MarkerAccessor(MarkerBehaviour target)
 {
     mTarget = target;
 }
 public static void RegisterMarker(MarkerBehaviour m)
 {
     allMakers.Add(m.GetMarkerID(), m);
 }
    // Use this for initialization
    void Start()
    {
        Debug.LogError ("Llamado al metodo START de ControllerAddInfoInMarker ************-->");
        /*
        info_add_select_button_enable = false;
        info_add_button_one_enable = false;
        info_add_button_two_enable = false;
        info_add_button_three_enable = false;
        info_add_button_four_enable = false;
        info_add_button_five_enable = false;
        info_add_button_six_enable = false;
        info_add_button_seven_enable = false;
        info_add_button_eight_enable = false;

        image_for_button_select = "";
        image_for_button_one = "";
        image_for_button_two = "";
        image_for_button_three = "";
        image_for_button_four = "";
        image_for_button_five = "";
        image_for_button_six = "";
        image_for_button_seven = "";
        image_for_button_eight = "";

        text_add_info_btn_one = "";
        text_add_info_btn_two = "";
        text_add_info_btn_three = "";
        text_add_info_btn_four = "";
        text_add_info_btn_five = "";
        text_add_info_btn_six = "";
        text_add_info_btn_seven = "";
        text_add_info_btn_eight = "";

        feedback_info_text_path = "Texts/errors/1_feedback_no_text";
        */
        mMarkerBehav = this.GetComponent<MarkerBehaviour> ();
    }
Example #32
0
 // Returns the Marker with the given unique ID.
 // Unique IDs for Markers are created when markers are registered.
 public bool TryGetMarkerByID(int id,
                              out MarkerBehaviour marker)
 {
     return(mMarkerBehaviourDict.TryGetValue(id, out marker));
 }
Example #33
0
    void OnTriggerEnter(Collider col)
    {
        if (col.gameObject.name == "Maqueta1" || col.gameObject.name == "Maqueta2" || col.gameObject.name == "Maqueta3")
        {
            //Debug.Log ("IGNORE");
        }
        else
        {
            if (this.gameObject.name == "Tablet1" || this.gameObject.name == "Tablet2" || this.gameObject.name == "Tablet3")
            {
                if (col.gameObject.name != "MarkerLeyenda1" && col.gameObject.name != "MarkerLeyenda2" && col.gameObject.name != "MarkerLeyenda3")           //Conos y control movimiento

                //col.gameObject.GetComponent<Renderer> ().material.color = colorToChange; //color del cono

                {
                    AnimationTrigger at = gameObject.GetComponent <AnimationTrigger>();
                    if (at.contenido != "Mesura" && at.contenido != "Plataforma")                       //Si es tapa
                    //if (at.contenido != "Mesura") {
                    {
                        MarkerFlicker mf = col.gameObject.GetComponent <MarkerFlicker> ();
                        //mf.c = colorToChange;
                    }
                    //Debug.Log (mb);
                    if (col.gameObject.name != "Tapa1")
                    {
                        MarkerBehaviour mb = col.gameObject.GetComponent <MarkerBehaviour>();

                        /*if(isSuperposition){
                         *      mb.isSuperposition=true;
                         * }*/
                        mb.animationDecision(at.contenido, this.gameObject.name, colorToChange);
                    }
                    //mb.StartState = true;
                    //Debug.Log ("HIT: "+col.gameObject.name);
                }
                if (col.gameObject.name == "Tapa1")               //control de la vision y el color
                {
                    AnimationTrigger at = gameObject.GetComponent <AnimationTrigger>();
                    if (at.contenido != "Mesura" && at.contenido != "Plataforma")
                    {
                        //if (at.contenido != "Mesura") {
                        LineRenderer line = col.gameObject.GetComponent <LineRenderer> ();
                        line.enabled = false;
                        TapaBehaviour tb = col.gameObject.GetComponent <TapaBehaviour> ();
                        tb.isNeuronal   = false;
                        tb.isPlataforma = false;
                        if (isSuperposition)
                        {
                            tb.isSuperposition = true;
                            tb.animationDecision("super", this.gameObject.name);

                            /*Material[] m = tb.GetComponent<Renderer>().materials;
                             * Color cv = m[1].color;
                             * cv.a = 1;
                             * m[1].color = cv; */
                        }
                        else
                        {
                            col.gameObject.GetComponent <Renderer> ().material.color = colorToChange;
                            MarkerFlicker mf = col.gameObject.GetComponent <MarkerFlicker> ();
                            //mf.c = colorToChange;
                        }
                        //cont++;
                        //Debug.Log ("HIT:NOT MESURA ");
                    }
                    else if (at.contenido == "Mesura" || at.contenido == "Plataforma")                      //Mesura y Plataforma
                    {
                        TapaBehaviour tb   = col.gameObject.GetComponent <TapaBehaviour> ();
                        LineRenderer  line = col.gameObject.GetComponent <LineRenderer> ();
                        line.enabled = false;

                        tb.animationDecision(at.contenido, this.gameObject.name);
                        //Debug.Log ("HIT:MESURA and PlAT "+at.contenido + "  "+this.gameObject.name);
                    }
                }
            }

            if (this.gameObject.name == "Tablet1Apagado" || this.gameObject.name == "Tablet2Apagado" || this.gameObject.name == "Tablet3Apagado")
            {
                if (col.gameObject.name != "Tapa1")
                {
                    MarkerBehaviour  mb = col.gameObject.GetComponent <MarkerBehaviour> ();
                    AnimationTrigger at = gameObject.GetComponent <AnimationTrigger> ();
                    //Debug.Log (col.gameObject.name);
                    //Debug.Log (mb);
                    mb.animationDecision(at.contenido, this.gameObject.name, colorToChange);
                    //Debug.Log ("HIT");
                }
                else
                {
                    TapaBehaviour tb = col.gameObject.GetComponent <TapaBehaviour> ();
                    tb.isNeuronal = false;
                }
            }
            if (this.gameObject.name == "ApagaSuperpos")
            {
                if (col.gameObject.name != "Tapa1")
                {
                    MarkerBehaviour  mb = col.gameObject.GetComponent <MarkerBehaviour> ();
                    AnimationTrigger at = gameObject.GetComponent <AnimationTrigger> ();
                    TapaBehaviour    tb = col.gameObject.GetComponent <TapaBehaviour> ();

                    //Debug.Log (col.gameObject.name);
                    //Debug.Log (mb);
                    mb.animationDecision(at.contenido, this.gameObject.name, colorToChange);
                    //tb.isSuperposition = false;
                    //Debug.Log ("HIT");
                }
                else
                {
                    TapaBehaviour tb = col.gameObject.GetComponent <TapaBehaviour> ();
                    tb.isNeuronal = false;
                    Material[] m  = tb.GetComponent <Renderer>().materials;
                    Color      cv = m[1].color;
                    cv.a       = 0;
                    m[1].color = cv;
                }
            }
            if (this.gameObject.name == "ControlJSonCollider")
            {
                GameObject sc = GameObject.Find("SceneControl");
                rmd = sc.GetComponent <ReadMunicipiData> ();
                //Debug.Log ("HITJSON");

                int code = col.gameObject.GetComponent <MarkerBehaviour> ().codigo;
                for (int i = 0; i < rmd.TodosMunicipios.Count; i++)
                {
                    //Debug.Log ("State:0 m1[i]:"+m1[i]+" Codigo:"+codigo);
                    if (code == rmd.TodosMunicipios [i].codigo)
                    {
                        float f = col.transform.position.y;
                        //float f=col.transform.parent.position.y;
                        Debug.Log("ParentPosy:" + f);
                        var v = rmd.TodosMunicipios [i];
                        v.posY = f;
                        rmd.TodosMunicipios[i] = v;
                        Debug.Log("Y nueva:" + rmd.TodosMunicipios[i].posY);
                        cont++;
                        Debug.Log("EscritosJson: " + cont);
                        break;
                    }
                }
            }
        }
    }
    private void InitializeMarkerBehaviour(MarkerBehaviour markerBehaviour, Marker marker)
    {
        IEditorMarkerBehaviour editorMarkerBehaviour = markerBehaviour;
        editorMarkerBehaviour.InitializeMarker(marker);
        if (!mTrackableBehaviours.ContainsKey(marker.ID))
        {
            // Add MarkerBehaviour to dictionary.
            mTrackableBehaviours[marker.ID] = markerBehaviour;

            Debug.Log("Found Marker named " + marker.Name +
                        " with id " + marker.ID);
        }
    }
Example #35
0
    public bool fillData()
    {
        Debug.Log("Fill Config");
        jsonString = File.ReadAllText(Application.dataPath + "/Resources/Json/DatosMunicipios.Json");
        if (jsonString == null)
        {
            return(false);
        }
        //itemData = JsonMapper.ToObject (jsonString);
        TodosMunicipios = new List <UnMunicipio> ();
        var N    = JSON.Parse(jsonString);
        int cont = 0;

        for (int i = 0; i < N.Count; i++)
        {
            um = new UnMunicipio();
            //scenes = new List<Escena> ();
            um.codigo = N [i] ["codigo"];
            um.nombre = N [i] ["nombre"];
            //Personas
            um.bibliotecas    = N [i] ["bibliotecas"];
            um.bibliobuses    = N [i] ["bibliobuses"];
            um.teleasistencia = N [i] ["teleasistencia"];
            um.hestia         = N [i] ["hestia"];
            um.governobert    = N [i] ["governobert"];
            um.xaloc          = N [i] ["xaloc"];
            um.km2            = N [i] ["km2"];
            //um.km22=N [i] ["KM22"];
            //Sostenibilidad
            um.CambioClimatico  = N [i] ["CambioClimatico"];
            um.Sostenibilidad   = N [i] ["Sostenibilidad"];
            um.EconomiaCircular = N [i] ["EconomiaCircular"];
            //um.emissions=N [i] ["emissions"];
            um.CalderesBiomassa    = N [i] ["CalderesBiomassa"];
            um.FotovoltaiquesAuto  = N [i] ["FotovoltaiquesAuto"];
            um.FotovoltaiquesVenta = N [i] ["FotovoltaiquesVenta"];
            um.AnalisisParticulas  = N [i] ["AnalisisParticulas"];
            um.AguaFuentes         = N [i] ["AguaFuentes"];
            um.MedidaSonido        = N [i] ["MedidaSonido"];
            um.SoporteTecnico      = N [i] ["SoporteTecnico"];
            um.AparatosPrestados   = N [i] ["AparatosPrestados"];
            um.Turismo             = N [i] ["Turismo"];
            //Tecnologia
            um.AsesoramientoJuridico = N [i] ["AsesoramientoJuridico"];
            um.GestionInformacion    = N [i] ["GestionInformacion"];
            um.GestionFormacion      = N [i] ["GestionFormacion"];
            um.HERMES = N [i] ["HERMES"];
            um.GestionContabilidad = N [i] ["GestionContabilidad"];
            um.GestionPadron       = N [i] ["GestionPadron"];
            um.GestionWebs         = N [i] ["GestionWebs"];
            um.Muniapps            = N [i] ["Muniapps"];
            um.PlataformaUrbana1   = N [i] ["PlataformaUrbana1"];
            um.PlataformaUrbana2   = N [i] ["PlataformaUrbana2"];
            um.Hibrid = N[i]["Hibrid"];
            um.SITMUN = N [i] ["SITMUN"];
            um.InfraestructurasInformacion = N [i] ["InfraestructurasInformacion"];
            //Posicion
            um.posX = N [i] ["posX"];
            um.posY = N [i] ["posY"];
            um.posZ = N [i] ["posZ"];

            TodosMunicipios.Add(um);

            //Debug.Log ("Nombre: "+um.nombre);
            //Debug.Log ("x: "+um.posX+" y: "+um.posY+" z: "+um.posZ);
            //if (um.bibliobuses != 0) {
            //Debug.Log ("Hay biblio: " + um.bibliotecas);
            cont++;
            GameObject Marker = Instantiate(marcador, new Vector3(um.posX, um.posY, um.posZ), Quaternion.identity);
            //GameObject Marker=Instantiate (marcador, new Vector3 (um.posX, um.posY, um.posZ), Quaternion.identity);
            Vector3 v = new Vector3(um.posX, um.posY, um.posZ);
            //v.y = -27;
            //Marker.transform.position= v;
            //GameObject Marker=Instantiate (marcador, new Vector3 (um.posX, um.posY, um.posZ), Quaternion.identity);
            //GameObject Marker=Instantiate (marcador, new Vector3 (um.posX, 70, um.posZ), Quaternion.identity);

            MarkerBehaviour MB = Marker.GetComponentInChildren <MarkerBehaviour> ();

            MB.codigo = um.codigo;
            MB.setYpos(um.posY);
            TapaBehaviour TB = Marker.GetComponentInChildren <TapaBehaviour> ();
            TB.codigo = um.codigo;
            //MB.pos = new Vector3 (um.posX,um.posY,um.posZ);
            //MB.yPos = um.posY;
            //Marker.transform.position= new Vector3 (um.posX,um.posY,um.posZ);
            Marker.transform.position = new Vector3(um.posX, um.posY - 27, um.posZ);
            //}
        }

        //LEYENDAS
        Debug.Log("Fill Config leyendas");
        jsonString = File.ReadAllText(Application.dataPath + "/Resources/Json/json_maqueta_es_en_ca.Json");
        if (jsonString == null)
        {
            Debug.Log("Error json");
            return(false);
        }
        TodasLeyendas = new List <Leyenda> ();
        var J     = JSON.Parse(jsonString);
        int conta = 0;

        Debug.Log("Temas:" + J.Count);
        for (int i = 0; i < J.Count; i++)
        {
            Debug.Log("Temas:" + i);

            Debug.Log("Contenidos tema:" + J[i]["contenidos"].Count);
            for (int j = 0; j < J[i]["contenidos"].Count; j++)
            {
                Debug.Log(" Subcontenidos:" + J [i] ["contenidos"] [j] ["Subcontenidos"].Count);
                if (J [i] ["contenidos"] [j] ["Subcontenidos"].Count > 0)
                {
                    ly = new Leyenda();
                    Debug.Log(" Rellena subcontenido");
                    for (int k = 0; k < J[i]["contenidos"][j]["Subcontenidos"].Count; k++)
                    {
                        ly.codigo      = J [i] ["contenidos"] [j] ["Subcontenidos"] [k] ["id"];
                        ly.codigoPadre = J [i] ["contenidos"] [j] ["id"];
                        ly.leyenda_esp = J [i] ["contenidos"] [j] ["Subcontenidos"] [k] ["idiomas"][0]["leyenda"];
                        ly.leyenda_ing = J [i] ["contenidos"] [j] ["Subcontenidos"] [k] ["idiomas"][1]["leyenda"];
                        ly.leyenda_cat = J [i] ["contenidos"] [j] ["Subcontenidos"] [k] ["idiomas"][2]["leyenda"];
                        Debug.Log("Codigo:" + ly.codigo + " leyenda" + ly.leyenda_esp);
                        TodasLeyendas.Add(ly);
                    }
                }
                else
                {
                    ly = new Leyenda();
                    Debug.Log(" Rellena contenido");
                    ly.codigo      = J [i] ["contenidos"] [j] ["id"];
                    ly.codigoPadre = J [i] ["contenidos"] [j] ["id"];
                    ly.leyenda_esp = J [i] ["contenidos"] [j] ["idiomas"] [0] ["leyenda"];
                    ly.leyenda_ing = J [i] ["contenidos"] [j] ["idiomas"] [1] ["leyenda"];
                    ly.leyenda_cat = J [i] ["contenidos"] [j] ["idiomas"] [2] ["leyenda"];
                    Debug.Log("Codigo:" + ly.codigo + " leyenda" + ly.leyenda_esp);
                    TodasLeyendas.Add(ly);
                }
            }
            Debug.Log("End for");
        }
        //FIN LEYENDAS


        Debug.Log("Datos recuperados. ");
        Debug.Log("Pintados: " + cont);
        //Instantiate(marcador,new Vector3(TodosMunicipios[0].posX,TodosMunicipios[0].posY,TodosMunicipios[0].posZ),Quaternion.identity);
        AnimationTrigger atScript = AnimStarters.GetComponent <AnimationTrigger>();

        //atScript.isGrowing = true;
        return(true);
    }
Example #36
0
 // The one MarkerBehaviour instance this accessor belongs to is set in the
 // constructor.
 public MarkerAccessor(MarkerBehaviour target)
 {
     mTarget = target;
 }
Example #37
0
 // Returns the Marker with the given unique ID.
 // Unique IDs for Markers are created when markers are registered.
 public bool TryGetMarkerByID(int id,
                              out MarkerBehaviour marker)
 {
     return mMarkerBehaviourDict.TryGetValue(id, out marker);
 }
    private static void CheckMesh(MarkerBehaviour mb)
    {
        // when copy-pasting targets between scenes, the mesh and materials of
        // the game objects get lost. This checks for them and re-creates them if they are found missing.
        GameObject mbObject = mb.gameObject;

        MeshFilter meshFilter = mbObject.GetComponent<MeshFilter>();
        if (meshFilter == null || meshFilter.sharedMesh == null)
        {
            CreateMesh(mb);
        }
    }
Example #39
0
    // Destroys the marker associated with the given MarkerBehaviour
    // at native code.
    public bool DestroyMarker(MarkerBehaviour marker, bool destroyGameObject)
    {
        if (markerTrackerDestroyMarker(marker.TrackableID) == 0)
        {
            Debug.LogError("Could not destroy marker with id " + marker.MarkerID + ".");
            return false;
        }

        mMarkerBehaviourDict.Remove(marker.TrackableID);

        if (destroyGameObject)
        {
            GameObject.Destroy(marker.gameObject);
        }

        // Tell QCARManager to reinitialize its trackable array.
        QCARManager.Instance.Reinit();

        return true;
    }
        void Start()
        {
            mTrackableBehaviour = GetComponent<TrackableBehaviour>();
            if (mTrackableBehaviour)
            {
                mTrackableBehaviour.RegisterTrackableEventHandler(this);
            }

            contadorOrdenes = 0;
            tracked = false;

            mMarkerBehav = GetComponent<MarkerBehaviour> ();
        }