Neodroid  0.2.0
Machine Learning Environment Prototyping Tool
DrawScreenSpaceBoundingBox.cs
Go to the documentation of this file.
1 using System.Collections.Generic;
2 using System.Linq;
3 using UnityEngine;
4 
5 namespace droid.Runtime.Utilities.GameObjects.BoundingBoxes {
9  [RequireComponent(typeof(Camera))]
10  [ExecuteInEditMode]
11  public class DrawScreenSpaceBoundingBox : MonoBehaviour {
12  List<string> _names = new List<string>();
13  List<Rect> _rects = new List<Rect>();
14  Camera _camera = null;
15 
16  [SerializeField] bool _draw_label = true;
17  [SerializeField] BoundingBox[] bounding_boxes = null;
18  [SerializeField] bool _cache_bounding_boxes = false;
19  [SerializeField] GUISkin gui_style = null;
20  [SerializeField] bool _draw_coords = false;
21 
22  void Awake() {
23  if (!this._camera) {
24  this._camera = this.GetComponent<Camera>();
25  }
26 
27  if (!this.gui_style) {
28  this.gui_style = Resources.FindObjectsOfTypeAll<GUISkin>().First(a => a.name == "BoundingBox");
29  }
30 
31  this.bounding_boxes = FindObjectsOfType<BoundingBox>();
32  }
33 
34  void Compute() {
35  this._rects.Clear();
36  this._names.Clear();
37 
38  if (!this._cache_bounding_boxes) {
39  this.bounding_boxes = FindObjectsOfType<BoundingBox>();
40  }
41 
42  foreach (var bb in this.bounding_boxes) {
43  if (this._camera.WorldToScreenPoint(bb.Bounds.center).z < 0) {
44  return;
45  }
46 
47  var a = bb.ScreenSpaceBoundingRect(this._camera);
48 
49  this._rects.Add(a);
50  this._names.Add(bb.name);
51  }
52  }
53 
54  void OnGUI() {
55  if (this.gui_style) {
56  GUI.skin = this.gui_style;
57  }
58 
59  this.Draw();
60  }
61 
62  void Draw() {
63  this.Compute();
64  var i = 0;
65  foreach (var rect in this._rects) {
66  var text = "";
67  if (this._draw_label) {
68  text += $"{this._names[i]}";
69  }
70 
71  if (this._draw_coords) {
72  text += $"\n{rect}\n{rect.center}";
73  }
74 
75  var a = rect;
76  a.y = Screen.height - (a.y + a.height);
77 
78  GUI.Box(a, text);
79 
80  i++;
81  }
82  }
83  }
84 }
Rect ScreenSpaceBoundingRect(Camera a_camera, float margin=0f)
Definition: BoundingBox.cs:225