Overte C++ Documentation
Avatar.h
1 //
2 // Avatar.h
3 // interface/src/avatar
4 //
5 // Copyright 2012 High Fidelity, Inc.
6 // Copyright 2021 Vircadia contributors.
7 //
8 // Distributed under the Apache License, Version 2.0.
9 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10 //
11 
12 #ifndef hifi_Avatar_h
13 #define hifi_Avatar_h
14 
15 #include <functional>
16 #include <glm/glm.hpp>
17 #include <glm/gtc/quaternion.hpp>
18 #include <map>
19 #include <set>
20 #include <vector>
21 
22 #include <QtCore/QUuid>
23 
24 #include <AvatarData.h>
25 #include <ShapeInfo.h>
26 #include <render/Scene.h>
27 #include <graphics-scripting/Forward.h>
28 #include <GLMHelpers.h>
29 #include <EntityItem.h>
30 
31 #include <Grab.h>
32 #include <ThreadSafeValueCache.h>
33 
34 #include "Head.h"
35 #include "SkeletonModel.h"
36 #include "Rig.h"
37 
38 #include "MetaModelPayload.h"
39 #include "MultiSphereShape.h"
40 
41 namespace render {
42  template <> const ItemKey payloadGetKey(const AvatarSharedPointer& avatar);
43  template <> const Item::Bound payloadGetBound(const AvatarSharedPointer& avatar, RenderArgs* args);
44  template <> void payloadRender(const AvatarSharedPointer& avatar, RenderArgs* args);
45  template <> uint32_t metaFetchMetaSubItems(const AvatarSharedPointer& avatar, ItemIDs& subItems);
46  template <> FadeProperties payloadGetFadeProperties(const AvatarSharedPointer& avatar, const TransitionType type);
47 }
48 
49 static const float SCALING_RATIO = .05f;
50 
51 extern const float CHAT_MESSAGE_SCALE;
52 extern const float CHAT_MESSAGE_HEIGHT;
53 
54 enum ScreenTintLayer {
55  SCREEN_TINT_BEFORE_LANDSCAPE = 0,
56  SCREEN_TINT_BEFORE_AVATARS,
57  SCREEN_TINT_BEFORE_MY_AVATAR,
58  SCREEN_TINT_AFTER_AVATARS,
59  NUM_SCREEN_TINT_LAYERS
60 };
61 
62 class Texture;
63 
64 class AvatarTransit {
65 public:
66  enum Status {
67  IDLE = 0,
68  STARTED,
69  PRE_TRANSIT,
70  START_TRANSIT,
71  TRANSITING,
72  END_TRANSIT,
73  POST_TRANSIT,
74  ENDED,
75  ABORT_TRANSIT
76  };
77 
78  enum EaseType {
79  NONE = 0,
80  EASE_IN,
81  EASE_OUT,
82  EASE_IN_OUT
83  };
84 
85  struct TransitConfig {
86  TransitConfig() {};
87  int _totalFrames { 0 };
88  float _framesPerMeter { 0.0f };
89  bool _isDistanceBased { false };
90  float _minTriggerDistance { 0.0f };
91  float _maxTriggerDistance { 0.0f };
92  float _abortDistance{ 0.0f };
93  EaseType _easeType { EaseType::EASE_OUT };
94  };
95 
96  AvatarTransit() {};
97  Status update(float deltaTime, const glm::vec3& avatarPosition, const TransitConfig& config);
98  void slamPosition(const glm::vec3& avatarPosition);
99  Status getStatus() { return _status; }
100  bool isActive() { return _isActive; }
101  glm::vec3 getCurrentPosition() { return _currentPosition; }
102  glm::vec3 getEndPosition() { return _endPosition; }
103  void setScale(float scale) { _scale = scale; }
104  void reset();
105 
106 private:
107  Status updatePosition(float deltaTime);
108  void start(float deltaTime, const glm::vec3& startPosition, const glm::vec3& endPosition, const TransitConfig& config);
109  float getEaseValue(AvatarTransit::EaseType type, float value);
110  bool _isActive { false };
111 
112  glm::vec3 _startPosition;
113  glm::vec3 _endPosition;
114  glm::vec3 _currentPosition;
115 
116  glm::vec3 _lastPosition;
117 
118  glm::vec3 _transitLine;
119  float _totalDistance { 0.0f };
120  float _preTransitTime { 0.0f };
121  float _totalTime { 0.0f };
122  float _transitTime { 0.0f };
123  float _postTransitTime { 0.0f };
124  float _currentTime { 0.0f };
125  EaseType _easeType { EaseType::EASE_OUT };
126  Status _status { Status::IDLE };
127  float _scale { 1.0f };
128 };
129 
130 class Avatar : public AvatarData, public scriptable::ModelProvider, public MetaModelPayload {
131  Q_OBJECT
132 
133  /*jsdoc
134  * @comment IMPORTANT: The JSDoc for the following properties should be copied to MyAvatar.h.
135  *
136  * @property {Vec3} skeletonOffset - Can be used to apply a translation offset between the avatar's position and the
137  * registration point of the 3D model.
138  */
139  Q_PROPERTY(glm::vec3 skeletonOffset READ getSkeletonOffset WRITE setSkeletonOffset)
140 
141 public:
142  static void setShowAvatars(bool render);
143  static void setShowReceiveStats(bool receiveStats);
144  static void setShowMyLookAtVectors(bool showMine);
145  static void setShowMyLookAtTarget(bool showMine);
146  static void setShowOtherLookAtVectors(bool showOthers);
147  static void setShowOtherLookAtTarget(bool showOthers);
148  static void setShowCollisionShapes(bool render);
149  static void setShowNamesAboveHeads(bool show);
150 
151  explicit Avatar(QThread* thread);
152  virtual ~Avatar();
153 
154  virtual void instantiableAvatar() = 0;
155 
156  typedef render::Payload<AvatarData> Payload;
157 
158  void init();
159  void removeAvatarEntitiesFromTree();
160  virtual void simulate(float deltaTime, bool inView) = 0;
161 
162  virtual void render(RenderArgs* renderArgs);
163 
164  void addToScene(AvatarSharedPointer self, const render::ScenePointer& scene,
165  render::Transaction& transaction);
166 
167  void removeFromScene(AvatarSharedPointer self, const render::ScenePointer& scene,
168  render::Transaction& transaction);
169 
170  void updateRenderItem(render::Transaction& transaction);
171 
172  virtual void postUpdate(float deltaTime, const render::ScenePointer& scene);
173 
174  //getters
175  bool isInitialized() const { return _initialized; }
176  SkeletonModelPointer getSkeletonModel() { return _skeletonModel; }
177  const SkeletonModelPointer getSkeletonModel() const { return _skeletonModel; }
178  glm::vec3 getChestPosition() const;
179  const Head* getHead() const { return static_cast<const Head*>(_headData); }
180  Head* getHead() { return static_cast<Head*>(_headData); }
181 
182  AABox getBounds() const;
183 
185  float getLODDistance() const;
186 
187  virtual void createOrb() { }
188 
189  enum class LoadingStatus {
190  NoModel,
191  LoadModel,
192  LoadSuccess,
193  LoadFailure
194  };
195  virtual void indicateLoadingStatus(LoadingStatus loadingStatus) { _loadingStatus = loadingStatus; }
196 
197  virtual QVector<glm::quat> getJointRotations() const override;
198  using AvatarData::getJointRotation;
199  virtual glm::quat getJointRotation(int index) const override;
200  virtual QVector<glm::vec3> getJointTranslations() const override;
201  using AvatarData::getJointTranslation;
202  virtual glm::vec3 getJointTranslation(int index) const override;
203  virtual int getJointIndex(const QString& name) const override;
204  virtual QStringList getJointNames() const override;
205 
206  std::vector<AvatarSkeletonTrait::UnpackedJointData> getSkeletonDefaultData();
207 
208  /*@jsdoc
209  * Gets the default rotation of a joint (in the current avatar) relative to its parent.
210  * <p>For information on the joint hierarchy used, see
211  * <a href="https://docs.overte.org/create/avatars/avatar-standards.html">Avatar Standards</a>.</p>
212  * @function MyAvatar.getDefaultJointRotation
213  * @param {number} index - The joint index.
214  * @returns {Quat} The default rotation of the joint if the joint index is valid, otherwise {@link Quat(0)|Quat.IDENTITY}.
215  */
216  Q_INVOKABLE virtual glm::quat getDefaultJointRotation(int index) const;
217 
218  /*@jsdoc
219  * Gets the default translation of a joint (in the current avatar) relative to its parent, in model coordinates.
220  * <p><strong>Warning:</strong> These coordinates are not necessarily in meters.</p>
221  * <p>For information on the joint hierarchy used, see
222  * <a href="https://docs.overte.org/create/avatars/avatar-standards.html">Avatar Standards</a>.</p>
223  * @function MyAvatar.getDefaultJointTranslation
224  * @param {number} index - The joint index.
225  * @returns {Vec3} The default translation of the joint (in model coordinates) if the joint index is valid, otherwise
226  * {@link Vec3(0)|Vec3.ZERO}.
227  */
228  Q_INVOKABLE virtual glm::vec3 getDefaultJointTranslation(int index) const;
229 
230  /*@jsdoc
231  * Gets the default joint rotations in avatar coordinates.
232  * The default pose of the avatar is defined by the position and orientation of all bones
233  * in the avatar's model file. Typically this is a T-pose.
234  * @function MyAvatar.getAbsoluteDefaultJointRotationInObjectFrame
235  * @param index {number} - The joint index.
236  * @returns {Quat} The default rotation of the joint in avatar coordinates.
237  * @example <caption>Report the default rotation of your avatar's head joint relative to your avatar.</caption>
238  * var headIndex = MyAvatar.getJointIndex("Head");
239  * var defaultHeadRotation = MyAvatar.getAbsoluteDefaultJointRotationInObjectFrame(headIndex);
240  * print("Default head rotation: " + JSON.stringify(Quat.safeEulerAngles(defaultHeadRotation))); // Degrees
241  */
242  Q_INVOKABLE virtual glm::quat getAbsoluteDefaultJointRotationInObjectFrame(int index) const;
243 
244  /*@jsdoc
245  * Gets the default joint translations in avatar coordinates.
246  * The default pose of the avatar is defined by the position and orientation of all bones
247  * in the avatar's model file. Typically this is a T-pose.
248  * @function MyAvatar.getAbsoluteDefaultJointTranslationInObjectFrame
249  * @param index {number} - The joint index.
250  * @returns {Vec3} The default position of the joint in avatar coordinates.
251  * @example <caption>Report the default translation of your avatar's head joint relative to your avatar.</caption>
252  * var headIndex = MyAvatar.getJointIndex("Head");
253  * var defaultHeadTranslation = MyAvatar.getAbsoluteDefaultJointTranslationInObjectFrame(headIndex);
254  * print("Default head translation: " + JSON.stringify(defaultHeadTranslation));
255  */
256  Q_INVOKABLE virtual glm::vec3 getAbsoluteDefaultJointTranslationInObjectFrame(int index) const;
257 
258 
259  virtual glm::vec3 getAbsoluteJointScaleInObjectFrame(int index) const override;
260  virtual glm::quat getAbsoluteJointRotationInObjectFrame(int index) const override;
261  virtual glm::vec3 getAbsoluteJointTranslationInObjectFrame(int index) const override;
262 
263  /*@jsdoc
264  * Sets the rotation of a joint relative to the avatar.
265  * <p><strong>Warning:</strong> Not able to be used in the <code>MyAvatar</code> API.</p>
266  * @function MyAvatar.setAbsoluteJointRotationInObjectFrame
267  * @param {number} index - The index of the joint. <em>Not used.</em>
268  * @param {Quat} rotation - The rotation of the joint relative to the avatar. <em>Not used.</em>
269  * @returns {boolean} <code>false</code>.
270  */
271  virtual bool setAbsoluteJointRotationInObjectFrame(int index, const glm::quat& rotation) override { return false; }
272 
273  /*@jsdoc
274  * Sets the translation of a joint relative to the avatar.
275  * <p><strong>Warning:</strong> Not able to be used in the <code>MyAvatar</code> API.</p>
276  * @function MyAvatar.setAbsoluteJointTranslationInObjectFrame
277  * @param {number} index - The index of the joint. <em>Not used.</em>
278  * @param {Vec3} translation - The translation of the joint relative to the avatar. <em>Not used.</em>
279  * @returns {boolean} <code>false</code>.
280  */
281  virtual bool setAbsoluteJointTranslationInObjectFrame(int index, const glm::vec3& translation) override { return false; }
282  virtual glm::vec3 getSpine2SplineOffset() const { return _spine2SplineOffset; }
283  virtual float getSpine2SplineRatio() const { return _spine2SplineRatio; }
284 
285  // world-space to avatar-space rigconversion functions
286  /*@jsdoc
287  * Transforms a position in world coordinates to a position in a joint's coordinates, or avatar coordinates if no joint is
288  * specified.
289  * @function MyAvatar.worldToJointPoint
290  * @param {Vec3} position - The position in world coordinates.
291  * @param {number} [jointIndex=-1] - The index of the joint.
292  * @returns {Vec3} The position in the joint's coordinate system, or avatar coordinate system if no joint is specified.
293  */
294  Q_INVOKABLE glm::vec3 worldToJointPoint(const glm::vec3& position, const int jointIndex = -1) const;
295 
296  /*@jsdoc
297  * Transforms a direction in world coordinates to a direction in a joint's coordinates, or avatar coordinates if no joint
298  * is specified.
299  * @function MyAvatar.worldToJointDirection
300  * @param {Vec3} direction - The direction in world coordinates.
301  * @param {number} [jointIndex=-1] - The index of the joint.
302  * @returns {Vec3} The direction in the joint's coordinate system, or avatar coordinate system if no joint is specified.
303  */
304  Q_INVOKABLE glm::vec3 worldToJointDirection(const glm::vec3& direction, const int jointIndex = -1) const;
305 
306  /*@jsdoc
307  * Transforms a rotation in world coordinates to a rotation in a joint's coordinates, or avatar coordinates if no joint is
308  * specified.
309  * @function MyAvatar.worldToJointRotation
310  * @param {Quat} rotation - The rotation in world coordinates.
311  * @param {number} [jointIndex=-1] - The index of the joint.
312  * @returns {Quat} The rotation in the joint's coordinate system, or avatar coordinate system if no joint is specified.
313  */
314  Q_INVOKABLE glm::quat worldToJointRotation(const glm::quat& rotation, const int jointIndex = -1) const;
315 
316  /*@jsdoc
317  * Transforms a position in a joint's coordinates, or avatar coordinates if no joint is specified, to a position in world
318  * coordinates.
319  * @function MyAvatar.jointToWorldPoint
320  * @param {Vec3} position - The position in joint coordinates, or avatar coordinates if no joint is specified.
321  * @param {number} [jointIndex=-1] - The index of the joint.
322  * @returns {Vec3} The position in world coordinates.
323  */
324  Q_INVOKABLE glm::vec3 jointToWorldPoint(const glm::vec3& position, const int jointIndex = -1) const;
325 
326  /*@jsdoc
327  * Transforms a direction in a joint's coordinates, or avatar coordinates if no joint is specified, to a direction in world
328  * coordinates.
329  * @function MyAvatar.jointToWorldDirection
330  * @param {Vec3} direction - The direction in joint coordinates, or avatar coordinates if no joint is specified.
331  * @param {number} [jointIndex=-1] - The index of the joint.
332  * @returns {Vec3} The direction in world coordinates.
333  */
334  Q_INVOKABLE glm::vec3 jointToWorldDirection(const glm::vec3& direction, const int jointIndex = -1) const;
335 
336  /*@jsdoc
337  * Transforms a rotation in a joint's coordinates, or avatar coordinates if no joint is specified, to a rotation in world
338  * coordinates.
339  * @function MyAvatar.jointToWorldRotation
340  * @param {Quat} rotation - The rotation in joint coordinates, or avatar coordinates if no joint is specified.
341  * @param {number} [jointIndex=-1] - The index of the joint.
342  * @returns {Quat} The rotation in world coordinates.
343  */
344  Q_INVOKABLE glm::quat jointToWorldRotation(const glm::quat& rotation, const int jointIndex = -1) const;
345 
346  Q_INVOKABLE virtual void setSkeletonModelURL(const QUrl& skeletonModelURL) override;
347 
348  void updateDisplayNameAlpha(bool showDisplayName);
349  virtual void setSessionDisplayName(const QString& sessionDisplayName) override { }; // no-op
350 
351  virtual int parseDataFromBuffer(const QByteArray& buffer) override;
352 
353  /*@jsdoc
354  * Sets the offset applied to the current avatar. The offset adjusts the position that the avatar is rendered. For example,
355  * with an offset of <code>{ x: 0, y: 0.1, z: 0 }</code>, your avatar will appear to be raised off the ground slightly.
356  * @function MyAvatar.setSkeletonOffset
357  * @param {Vec3} offset - The skeleton offset to set.
358  * @example <caption>Raise your avatar off the ground a little.</caption>
359  * // Raise your avatar off the ground a little.
360  * MyAvatar.setSkeletonOffset({ x: 0, y: 0.1, z: 0 });
361  *
362  * // Restore its offset after 5s.
363  * Script.setTimeout(function () {
364  * MyAvatar.setSkeletonOffset(Vec3.ZERO);
365  * }, 5000);
366  */
367  Q_INVOKABLE void setSkeletonOffset(const glm::vec3& offset);
368 
369  /*@jsdoc
370  * Gets the offset applied to the current avatar. The offset adjusts the position that the avatar is rendered. For example,
371  * with an offset of <code>{ x: 0, y: 0.1, z: 0 }</code>, your avatar will appear to be raised off the ground slightly.
372  * @function MyAvatar.getSkeletonOffset
373  * @returns {Vec3} The current skeleton offset.
374  * @example <caption>Report your avatar's current skeleton offset.</caption>
375  * print(JSON.stringify(MyAvatar.getSkeletonOffset()));
376  */
377  Q_INVOKABLE glm::vec3 getSkeletonOffset() { return _skeletonOffset; }
378 
379  virtual glm::vec3 getSkeletonPosition() const;
380 
381  /*@jsdoc
382  * Gets the position of a joint in the current avatar.
383  * @function MyAvatar.getJointPosition
384  * @param {number} index - The index of the joint.
385  * @returns {Vec3} The position of the joint in world coordinates.
386  */
387  Q_INVOKABLE glm::vec3 getJointPosition(int index) const;
388 
389  /*@jsdoc
390  * Gets the position of a joint in the current avatar.
391  * @function MyAvatar.getJointPosition
392  * @param {string} name - The name of the joint.
393  * @returns {Vec3} The position of the joint in world coordinates.
394  * @example <caption>Report the position of your avatar's hips.</caption>
395  * print(JSON.stringify(MyAvatar.getJointPosition("Hips")));
396  */
397  Q_INVOKABLE glm::vec3 getJointPosition(const QString& name) const;
398 
399  /*@jsdoc
400  * Gets the position of the current avatar's neck in world coordinates.
401  * @function MyAvatar.getNeckPosition
402  * @returns {Vec3} The position of the neck in world coordinates.
403  * @example <caption>Report the position of your avatar's neck.</caption>
404  * print(JSON.stringify(MyAvatar.getNeckPosition()));
405  */
406  Q_INVOKABLE glm::vec3 getNeckPosition() const;
407 
408  /*@jsdoc
409  * Gets the current acceleration of the avatar.
410  * @function MyAvatar.getAcceleration
411  * @returns {Vec3} The current acceleration of the avatar.
412  */
413  Q_INVOKABLE glm::vec3 getAcceleration() const { return _acceleration; }
414 
417  void scaleVectorRelativeToPosition(glm::vec3& positionToScale) const;
418 
419  void slamPosition(const glm::vec3& position);
420  virtual void updateAttitude(const glm::quat& orientation) override;
421 
422  // Call this when updating Avatar position with a delta. This will allow us to
423  // _accurately_ measure position changes and compute the resulting velocity
424  // (otherwise floating point error will cause problems at large positions).
425  void applyPositionDelta(const glm::vec3& delta);
426 
427  virtual void rebuildCollisionShape() = 0;
428 
429  virtual void computeShapeInfo(ShapeInfo& shapeInfo);
430  virtual void computeDetailedShapeInfo(ShapeInfo& shapeInfo, int jointIndex);
431 
432  void getCapsule(glm::vec3& start, glm::vec3& end, float& radius);
433  float computeMass();
434  /*@jsdoc
435  * Gets the position of the current avatar's feet (or rather, bottom of its collision capsule) in world coordinates.
436  * @function MyAvatar.getWorldFeetPosition
437  * @returns {Vec3} The position of the avatar's feet in world coordinates.
438  */
439  Q_INVOKABLE glm::vec3 getWorldFeetPosition();
440 
441  void setPositionViaScript(const glm::vec3& position) override;
442  void setOrientationViaScript(const glm::quat& orientation) override;
443 
444  /*@jsdoc
445  * Gets the ID of the entity or avatar that the avatar is parented to.
446  * @function MyAvatar.getParentID
447  * @returns {Uuid} The ID of the entity or avatar that the avatar is parented to. {@link Uuid(0)|Uuid.NONE} if not parented.
448  */
449  // This calls through to the SpatiallyNestable versions, but is here to expose these to JavaScript.
450  Q_INVOKABLE virtual const QUuid getParentID() const override { return SpatiallyNestable::getParentID(); }
451 
452  /*@jsdoc
453  * Sets the ID of the entity or avatar that the avatar is parented to.
454  * @function MyAvatar.setParentID
455  * @param {Uuid} parentID - The ID of the entity or avatar that the avatar should be parented to. Set to
456  * {@link Uuid(0)|Uuid.NONE} to unparent.
457  */
458  // This calls through to the SpatiallyNestable versions, but is here to expose these to JavaScript.
459  Q_INVOKABLE virtual void setParentID(const QUuid& parentID) override;
460 
461  /*@jsdoc
462  * Gets the joint of the entity or avatar that the avatar is parented to.
463  * @function MyAvatar.getParentJointIndex
464  * @returns {number} The joint of the entity or avatar that the avatar is parented to. <code>65535</code> or
465  * <code>-1</code> if parented to the entity or avatar's position and orientation rather than a joint.
466  */
467  // This calls through to the SpatiallyNestable versions, but is here to expose these to JavaScript.
468  Q_INVOKABLE virtual quint16 getParentJointIndex() const override { return SpatiallyNestable::getParentJointIndex(); }
469 
470  /*@jsdoc
471  * Sets the joint of the entity or avatar that the avatar is parented to.
472  * @function MyAvatar.setParentJointIndex
473  * @param {number} parentJointIndex - The joint of the entity or avatar that the avatar should be parented to. Use
474  * <code>65535</code> or <code>-1</code> to parent to the entity or avatar's position and orientation rather than a
475  * joint.
476  */
477  // This calls through to the SpatiallyNestable versions, but is here to expose these to JavaScript.
478  Q_INVOKABLE virtual void setParentJointIndex(quint16 parentJointIndex) override;
479 
480  /*@jsdoc
481  * Gets information on all the joints in the avatar's skeleton.
482  * @function MyAvatar.getSkeleton
483  * @returns {SkeletonJoint[]} Information about each joint in the avatar's skeleton.
484  */
485  Q_INVOKABLE QList<QVariant> getSkeleton();
486 
487  // NOT thread safe, must be called on main thread.
488  glm::vec3 getUncachedLeftPalmPosition() const;
489  glm::quat getUncachedLeftPalmRotation() const;
490  glm::vec3 getUncachedRightPalmPosition() const;
491  glm::quat getUncachedRightPalmRotation() const;
492 
493  uint64_t getLastRenderUpdateTime() const { return _lastRenderUpdateTime; }
494  void setLastRenderUpdateTime(uint64_t time) { _lastRenderUpdateTime = time; }
495 
496  void animateScaleChanges(float deltaTime);
497  void setTargetScale(float targetScale) override;
498  float getTargetScale() const { return _targetScale; }
499 
500  /*@jsdoc
501  * @function MyAvatar.getSimulationRate
502  * @param {AvatarSimulationRate} [rateName=""] - Rate name.
503  * @returns {number} Simulation rate in Hz.
504  * @deprecated This function is deprecated and will be removed.
505  */
506  Q_INVOKABLE float getSimulationRate(const QString& rateName = QString("")) const;
507 
508  bool hasNewJointData() const { return _hasNewJointData; }
509 
510  float getBoundingRadius() const;
511  AABox getRenderBounds() const; // THis call is accessible from rendering thread only to report the bounding box of the avatar during the frame.
512  AABox getFitBounds() const { return _fitBoundingBox; }
513 
514  void addToScene(AvatarSharedPointer self, const render::ScenePointer& scene);
515  void ensureInScene(AvatarSharedPointer self, const render::ScenePointer& scene);
516  bool isInScene() const { return render::Item::isValidID(_renderItemID); }
517  render::ItemID getRenderItemID() { return _renderItemID; }
518  bool isMoving() const { return _moving; }
519 
520  void fadeIn(render::ScenePointer scene);
521  void fadeOut(render::Transaction& transaction, KillAvatarReason reason);
522  TransitionType getLastFadeRequested() const;
523  FadeProperties getFadeProperties(const TransitionType type) const;
524 
525  // JSDoc is in AvatarData.h.
526  Q_INVOKABLE virtual float getEyeHeight() const override;
527 
528  // returns eye height of avatar in meters, ignoring avatar scale.
529  // if _targetScale is 1 then this will be identical to getEyeHeight.
530  virtual float getUnscaledEyeHeight() const override;
531 
532  // returns true, if an acurate eye height estimage can be obtained by inspecting the avatar model skeleton and geometry,
533  // not all subclasses of AvatarData have access to this data.
534  virtual bool canMeasureEyeHeight() const override { return true; }
535 
536  virtual float getModelScale() const { return _modelScale; }
537  virtual void setModelScale(float scale) { _modelScale = scale; }
538  virtual glm::vec3 scaleForChildren() const override { return glm::vec3(getModelScale()); }
539 
540  // Show hide the model representation of the avatar
541  virtual void setEnableMeshVisible(bool isEnabled);
542  virtual bool getEnableMeshVisible() const;
543 
544  void addMaterial(graphics::MaterialLayer material, const std::string& parentMaterialName);
545  void removeMaterial(graphics::MaterialPointer material, const std::string& parentMaterialName);
546 
547  virtual scriptable::ScriptableModelBase getScriptableModel() override;
548 
549  std::shared_ptr<AvatarTransit> getTransit() { return std::make_shared<AvatarTransit>(_transit); };
550  AvatarTransit::Status updateTransit(float deltaTime, const glm::vec3& avatarPosition, float avatarScale, const AvatarTransit::TransitConfig& config);
551 
552  void accumulateGrabPositions(std::map<QUuid, GrabLocationAccumulator>& grabAccumulators);
553 
554  const std::vector<MultiSphereShape>& getMultiSphereShapes() const { return _multiSphereShapes; }
555  void tearDownGrabs();
556 
557  uint32_t appendSubMetaItems(render::ItemIDs& subItems);
558 
559  virtual bool shouldRender() const { return _isMeshVisible && _isReadyToDraw; }
560 
561  static const float MYAVATAR_ENTITY_LOADING_PRIORITY;
562  static const float OTHERAVATAR_ENTITY_LOADING_PRIORITY;
563 
564 signals:
565  /*@jsdoc
566  * Triggered when the avatar's target scale is changed. The target scale is the desired scale of the avatar without any
567  * restrictions on permissible scale values imposed by the domain.
568  * @function MyAvatar.targetScaleChanged
569  * @param {number} targetScale - The avatar's target scale.
570  * @returns Signal
571  */
572  void targetScaleChanged(float targetScale);
573 
574 public slots:
575 
576  // FIXME - these should be migrated to use Pose data instead
577  // thread safe, will return last valid palm from cache
578 
579  /*@jsdoc
580  * Gets the position of the left palm in world coordinates.
581  * @function MyAvatar.getLeftPalmPosition
582  * @returns {Vec3} The position of the left palm in world coordinates.
583  * @example <caption>Report the position of your avatar's left palm.</caption>
584  * print(JSON.stringify(MyAvatar.getLeftPalmPosition()));
585  */
586  glm::vec3 getLeftPalmPosition() const;
587 
588  /*@jsdoc
589  * Gets the rotation of the left palm in world coordinates.
590  * @function MyAvatar.getLeftPalmRotation
591  * @returns {Quat} The rotation of the left palm in world coordinates.
592  * @example <caption>Report the rotation of your avatar's left palm.</caption>
593  * print(JSON.stringify(MyAvatar.getLeftPalmRotation()));
594  */
595  glm::quat getLeftPalmRotation() const;
596 
597  /*@jsdoc
598  * Gets the position of the right palm in world coordinates.
599  * @function MyAvatar.getRightPalmPosition
600  * @returns {Vec3} The position of the right palm in world coordinates.
601  * @example <caption>Report the position of your avatar's right palm.</caption>
602  * print(JSON.stringify(MyAvatar.getRightPalmPosition()));
603  */
604  glm::vec3 getRightPalmPosition() const;
605 
606  /*@jsdoc
607  * Get the rotation of the right palm in world coordinates.
608  * @function MyAvatar.getRightPalmRotation
609  * @returns {Quat} The rotation of the right palm in world coordinates.
610  * @example <caption>Report the rotation of your avatar's right palm.</caption>
611  * print(JSON.stringify(MyAvatar.getRightPalmRotation()));
612  */
613  glm::quat getRightPalmRotation() const;
614 
615  /*@jsdoc
616  * @function MyAvatar.setModelURLFinished
617  * @param {boolean} success
618  * @deprecated This function is deprecated and will be removed.
619  */
620  // hooked up to Model::setURLFinished signal
621  void setModelURLFinished(bool success);
622 
623  /*@jsdoc
624  * @function MyAvatar.rigReady
625  * @deprecated This function is deprecated and will be removed.
626  */
627  // Hooked up to Model::rigReady signal
628  void rigReady();
629 
630  /*@jsdoc
631  * @function MyAvatar.rigReset
632  * @deprecated This function is deprecated and will be removed.
633  */
634  // Hooked up to Model::rigReset signal
635  void rigReset();
636 
637 protected:
638  float getUnscaledEyeHeightFromSkeleton() const;
639  void buildUnscaledEyeHeightCache();
640  void buildSpine2SplineRatioCache();
641  void clearUnscaledEyeHeightCache();
642  void clearSpine2SplineRatioCache();
643  virtual const QString& getSessionDisplayNameForTransport() const override { return _empty; } // Save a tiny bit of bandwidth. Mixer won't look at what we send.
644  QString _empty{};
645  virtual void maybeUpdateSessionDisplayNameFromTransport(const QString& sessionDisplayName) override { _sessionDisplayName = sessionDisplayName; } // don't use no-op setter!
646  void computeMultiSphereShapes();
647  void updateFitBoundingBox();
648 
649  SkeletonModelPointer _skeletonModel;
650 
651  void invalidateJointIndicesCache() const;
652  void withValidJointIndicesCache(std::function<void()> const& worker) const;
653  mutable QHash<QString, int> _modelJointIndicesCache;
654  mutable QReadWriteLock _modelJointIndicesCacheLock;
655  mutable bool _modelJointsCached { false };
656 
657  glm::vec3 _skeletonOffset;
658 
659  float _bodyYawDelta { 0.0f }; // degrees/sec
660  float _seatedBodyYawDelta{ 0.0f }; // degrees/renderframe
661 
662  // These position histories and derivatives are in the world-frame.
663  // The derivatives are the MEASURED results of all external and internal forces
664  // and are therefore READ-ONLY --> motion control of the Avatar is NOT obtained
665  // by setting these values.
666  // Floating point error prevents us from accurately measuring velocity using a naive approach
667  // (e.g. vel = (pos - lastPos)/dt) so instead we use _positionDeltaAccumulator.
668  glm::vec3 _positionDeltaAccumulator;
669  glm::vec3 _lastVelocity;
670  glm::vec3 _acceleration;
671  glm::vec3 _angularVelocity;
672  glm::vec3 _lastAngularVelocity;
673  glm::vec3 _angularAcceleration;
674  glm::quat _lastOrientation;
675  glm::vec3 _worldUpDirection { Vectors::UP };
676  bool _moving { false };
677 
678  // protected methods...
679  bool isLookingAtMe(AvatarSharedPointer avatar) const;
680  virtual void sendPacket(const QUuid& entityID) const { }
681  bool applyGrabChanges();
682  void relayJointDataToChildren();
683 
684  void fade(render::Transaction& transaction, TransitionType type);
685 
686  glm::vec3 getBodyRightDirection() const { return getWorldOrientation() * IDENTITY_RIGHT; }
687  glm::vec3 getBodyUpDirection() const { return getWorldOrientation() * IDENTITY_UP; }
688  void measureMotionDerivatives(float deltaTime);
689  bool getCollideWithOtherAvatars() const { return _collideWithOtherAvatars; }
690 
691  float getSkeletonHeight() const;
692  float getHeadHeight() const;
693  float getPelvisFloatingHeight() const;
694  glm::vec3 getDisplayNamePosition() const;
695 
696  Transform calculateDisplayNameTransform(const ViewFrustum& view, const glm::vec3& textPosition) const;
697  void renderDisplayName(gpu::Batch& batch, const ViewFrustum& view, const glm::vec3& textPosition, bool forward) const;
698  virtual bool shouldRenderHead(const RenderArgs* renderArgs) const;
699  virtual void fixupModelsInScene(const render::ScenePointer& scene);
700 
701  virtual void updatePalms();
702 
703  render::ItemID _renderItemID{ render::Item::INVALID_ITEM_ID };
704  TransitionType _lastFadeRequested { TransitionType::NONE }; // Used for sanity checking
705 
706  ThreadSafeValueCache<glm::vec3> _leftPalmPositionCache { glm::vec3() };
707  ThreadSafeValueCache<glm::quat> _leftPalmRotationCache { glm::quat() };
708  ThreadSafeValueCache<glm::vec3> _rightPalmPositionCache { glm::vec3() };
709  ThreadSafeValueCache<glm::quat> _rightPalmRotationCache { glm::quat() };
710 
711  // Some rate tracking support
712  RateCounter<> _simulationRate;
713  RateCounter<> _simulationInViewRate;
714  RateCounter<> _skeletonModelSimulationRate;
715  RateCounter<> _jointDataSimulationRate;
716 
717  class AvatarEntityDataHash {
718  public:
719  AvatarEntityDataHash(uint32_t h) : hash(h) {};
720  uint32_t hash { 0 };
721  bool success { false };
722  };
723 
724  uint64_t _lastRenderUpdateTime { 0 };
725  int _leftPointerGeometryID { 0 };
726  int _rightPointerGeometryID { 0 };
727  int _nameRectGeometryID { 0 };
728  bool _initialized { false };
729  bool _isAnimatingScale { false };
730  bool _mustFadeIn { false };
731  bool _reconstructSoftEntitiesJointMap { false };
732  float _modelScale { 1.0f };
733 
734  AvatarTransit _transit;
735  std::mutex _transitLock;
736 
737  int _voiceSphereID;
738 
739  float _displayNameTargetAlpha { 1.0f };
740  float _displayNameAlpha { 1.0f };
741 
742  ThreadSafeValueCache<float> _unscaledEyeHeightCache { DEFAULT_AVATAR_EYE_HEIGHT };
743  float _spine2SplineRatio { DEFAULT_SPINE2_SPLINE_PROPORTION };
744  glm::vec3 _spine2SplineOffset;
745 
746  std::unordered_map<std::string, graphics::MultiMaterial> _materials;
747  std::mutex _materialsLock;
748 
749  void processMaterials();
750 
751  AABox _renderBound;
752  bool _isMeshVisible { true };
753  bool _needMeshVisibleSwitch { true };
754  bool _isReadyToDraw { false };
755  bool _needsWearablesLoadedCheck { false };
756  bool _hasCheckedForAvatarEntities { false };
757 
758  static const float MYAVATAR_LOADING_PRIORITY;
759  static const float OTHERAVATAR_LOADING_PRIORITY;
760 
761  LoadingStatus _loadingStatus { LoadingStatus::NoModel };
762 
763  static void metaBlendshapeOperator(render::ItemID renderItemID, int blendshapeNumber, const QVector<BlendshapeOffset>& blendshapeOffsets,
764  const QVector<int>& blendedMeshSizes, const render::ItemIDs& subItemIDs);
765 
766  std::vector<MultiSphereShape> _multiSphereShapes;
767  AABox _fitBoundingBox;
768  void clearAvatarGrabData(const QUuid& grabID) override;
769 
770  using SetOfIDs = std::set<QUuid>;
771  using VectorOfIDs = std::vector<QUuid>;
772  using MapOfGrabs = std::map<QUuid, GrabPointer>;
773 
774  MapOfGrabs _avatarGrabs;
775  SetOfIDs _grabsToChange; // updated grab IDs -- changes needed to entities or physics
776  VectorOfIDs _grabsToDelete; // deleted grab IDs -- changes needed to entities or physics
777 
778  ReadWriteLockable _subItemLock;
779  void updateDescendantRenderIDs();
780  render::ItemIDs _descendantRenderIDs;
781  std::unordered_set<EntityItemID> _renderingDescendantEntityIDs;
782 };
783 
784 #endif // hifi_Avatar_h
A simple object wrapper for an OpenGL texture.
Definition: material-networking/src/material-networking/TextureCache.h:39