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 }
47 
48 static const float SCALING_RATIO = .05f;
49 
50 extern const float CHAT_MESSAGE_SCALE;
51 extern const float CHAT_MESSAGE_HEIGHT;
52 
53 enum ScreenTintLayer {
54  SCREEN_TINT_BEFORE_LANDSCAPE = 0,
55  SCREEN_TINT_BEFORE_AVATARS,
56  SCREEN_TINT_BEFORE_MY_AVATAR,
57  SCREEN_TINT_AFTER_AVATARS,
58  NUM_SCREEN_TINT_LAYERS
59 };
60 
61 class Texture;
62 
63 class AvatarTransit {
64 public:
65  enum Status {
66  IDLE = 0,
67  STARTED,
68  PRE_TRANSIT,
69  START_TRANSIT,
70  TRANSITING,
71  END_TRANSIT,
72  POST_TRANSIT,
73  ENDED,
74  ABORT_TRANSIT
75  };
76 
77  enum EaseType {
78  NONE = 0,
79  EASE_IN,
80  EASE_OUT,
81  EASE_IN_OUT
82  };
83 
84  struct TransitConfig {
85  TransitConfig() {};
86  int _totalFrames { 0 };
87  float _framesPerMeter { 0.0f };
88  bool _isDistanceBased { false };
89  float _minTriggerDistance { 0.0f };
90  float _maxTriggerDistance { 0.0f };
91  float _abortDistance{ 0.0f };
92  EaseType _easeType { EaseType::EASE_OUT };
93  };
94 
95  AvatarTransit() {};
96  Status update(float deltaTime, const glm::vec3& avatarPosition, const TransitConfig& config);
97  void slamPosition(const glm::vec3& avatarPosition);
98  Status getStatus() { return _status; }
99  bool isActive() { return _isActive; }
100  glm::vec3 getCurrentPosition() { return _currentPosition; }
101  glm::vec3 getEndPosition() { return _endPosition; }
102  void setScale(float scale) { _scale = scale; }
103  void reset();
104 
105 private:
106  Status updatePosition(float deltaTime);
107  void start(float deltaTime, const glm::vec3& startPosition, const glm::vec3& endPosition, const TransitConfig& config);
108  float getEaseValue(AvatarTransit::EaseType type, float value);
109  bool _isActive { false };
110 
111  glm::vec3 _startPosition;
112  glm::vec3 _endPosition;
113  glm::vec3 _currentPosition;
114 
115  glm::vec3 _lastPosition;
116 
117  glm::vec3 _transitLine;
118  float _totalDistance { 0.0f };
119  float _preTransitTime { 0.0f };
120  float _totalTime { 0.0f };
121  float _transitTime { 0.0f };
122  float _postTransitTime { 0.0f };
123  float _currentTime { 0.0f };
124  EaseType _easeType { EaseType::EASE_OUT };
125  Status _status { Status::IDLE };
126  float _scale { 1.0f };
127 };
128 
129 class Avatar : public AvatarData, public scriptable::ModelProvider, public MetaModelPayload {
130  Q_OBJECT
131 
132  /*jsdoc
133  * @comment IMPORTANT: The JSDoc for the following properties should be copied to MyAvatar.h.
134  *
135  * @property {Vec3} skeletonOffset - Can be used to apply a translation offset between the avatar's position and the
136  * registration point of the 3D model.
137  */
138  Q_PROPERTY(glm::vec3 skeletonOffset READ getSkeletonOffset WRITE setSkeletonOffset)
139 
140 public:
141  static void setShowAvatars(bool render);
142  static void setShowReceiveStats(bool receiveStats);
143  static void setShowMyLookAtVectors(bool showMine);
144  static void setShowMyLookAtTarget(bool showMine);
145  static void setShowOtherLookAtVectors(bool showOthers);
146  static void setShowOtherLookAtTarget(bool showOthers);
147  static void setShowCollisionShapes(bool render);
148  static void setShowNamesAboveHeads(bool show);
149 
150  explicit Avatar(QThread* thread);
151  virtual ~Avatar();
152 
153  virtual void instantiableAvatar() = 0;
154 
155  typedef render::Payload<AvatarData> Payload;
156 
157  void init();
158  void removeAvatarEntitiesFromTree();
159  virtual void simulate(float deltaTime, bool inView) = 0;
160  virtual void simulateAttachments(float deltaTime);
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  virtual void setAttachmentData(const QVector<AttachmentData>& attachmentData) override;
348 
349  void updateDisplayNameAlpha(bool showDisplayName);
350  virtual void setSessionDisplayName(const QString& sessionDisplayName) override { }; // no-op
351 
352  virtual int parseDataFromBuffer(const QByteArray& buffer) override;
353 
354  /*@jsdoc
355  * Sets the offset applied to the current avatar. The offset adjusts the position that the avatar is rendered. For example,
356  * with an offset of <code>{ x: 0, y: 0.1, z: 0 }</code>, your avatar will appear to be raised off the ground slightly.
357  * @function MyAvatar.setSkeletonOffset
358  * @param {Vec3} offset - The skeleton offset to set.
359  * @example <caption>Raise your avatar off the ground a little.</caption>
360  * // Raise your avatar off the ground a little.
361  * MyAvatar.setSkeletonOffset({ x: 0, y: 0.1, z: 0 });
362  *
363  * // Restore its offset after 5s.
364  * Script.setTimeout(function () {
365  * MyAvatar.setSkeletonOffset(Vec3.ZERO);
366  * }, 5000);
367  */
368  Q_INVOKABLE void setSkeletonOffset(const glm::vec3& offset);
369 
370  /*@jsdoc
371  * Gets the offset applied to the current avatar. The offset adjusts the position that the avatar is rendered. For example,
372  * with an offset of <code>{ x: 0, y: 0.1, z: 0 }</code>, your avatar will appear to be raised off the ground slightly.
373  * @function MyAvatar.getSkeletonOffset
374  * @returns {Vec3} The current skeleton offset.
375  * @example <caption>Report your avatar's current skeleton offset.</caption>
376  * print(JSON.stringify(MyAvatar.getSkeletonOffset()));
377  */
378  Q_INVOKABLE glm::vec3 getSkeletonOffset() { return _skeletonOffset; }
379 
380  virtual glm::vec3 getSkeletonPosition() const;
381 
382  /*@jsdoc
383  * Gets the position of a joint in the current avatar.
384  * @function MyAvatar.getJointPosition
385  * @param {number} index - The index of the joint.
386  * @returns {Vec3} The position of the joint in world coordinates.
387  */
388  Q_INVOKABLE glm::vec3 getJointPosition(int index) const;
389 
390  /*@jsdoc
391  * Gets the position of a joint in the current avatar.
392  * @function MyAvatar.getJointPosition
393  * @param {string} name - The name of the joint.
394  * @returns {Vec3} The position of the joint in world coordinates.
395  * @example <caption>Report the position of your avatar's hips.</caption>
396  * print(JSON.stringify(MyAvatar.getJointPosition("Hips")));
397  */
398  Q_INVOKABLE glm::vec3 getJointPosition(const QString& name) const;
399 
400  /*@jsdoc
401  * Gets the position of the current avatar's neck in world coordinates.
402  * @function MyAvatar.getNeckPosition
403  * @returns {Vec3} The position of the neck in world coordinates.
404  * @example <caption>Report the position of your avatar's neck.</caption>
405  * print(JSON.stringify(MyAvatar.getNeckPosition()));
406  */
407  Q_INVOKABLE glm::vec3 getNeckPosition() const;
408 
409  /*@jsdoc
410  * Gets the current acceleration of the avatar.
411  * @function MyAvatar.getAcceleration
412  * @returns {Vec3} The current acceleration of the avatar.
413  */
414  Q_INVOKABLE glm::vec3 getAcceleration() const { return _acceleration; }
415 
418  void scaleVectorRelativeToPosition(glm::vec3& positionToScale) const;
419 
420  void slamPosition(const glm::vec3& position);
421  virtual void updateAttitude(const glm::quat& orientation) override;
422 
423  // Call this when updating Avatar position with a delta. This will allow us to
424  // _accurately_ measure position changes and compute the resulting velocity
425  // (otherwise floating point error will cause problems at large positions).
426  void applyPositionDelta(const glm::vec3& delta);
427 
428  virtual void rebuildCollisionShape() = 0;
429 
430  virtual void computeShapeInfo(ShapeInfo& shapeInfo);
431  virtual void computeDetailedShapeInfo(ShapeInfo& shapeInfo, int jointIndex);
432 
433  void getCapsule(glm::vec3& start, glm::vec3& end, float& radius);
434  float computeMass();
435  /*@jsdoc
436  * Gets the position of the current avatar's feet (or rather, bottom of its collision capsule) in world coordinates.
437  * @function MyAvatar.getWorldFeetPosition
438  * @returns {Vec3} The position of the avatar's feet in world coordinates.
439  */
440  Q_INVOKABLE glm::vec3 getWorldFeetPosition();
441 
442  void setPositionViaScript(const glm::vec3& position) override;
443  void setOrientationViaScript(const glm::quat& orientation) override;
444 
445  /*@jsdoc
446  * Gets the ID of the entity or avatar that the avatar is parented to.
447  * @function MyAvatar.getParentID
448  * @returns {Uuid} The ID of the entity or avatar that the avatar is parented to. {@link Uuid(0)|Uuid.NULL} if not parented.
449  */
450  // This calls through to the SpatiallyNestable versions, but is here to expose these to JavaScript.
451  Q_INVOKABLE virtual const QUuid getParentID() const override { return SpatiallyNestable::getParentID(); }
452 
453  /*@jsdoc
454  * Sets the ID of the entity or avatar that the avatar is parented to.
455  * @function MyAvatar.setParentID
456  * @param {Uuid} parentID - The ID of the entity or avatar that the avatar should be parented to. Set to
457  * {@link Uuid(0)|Uuid.NULL} to unparent.
458  */
459  // This calls through to the SpatiallyNestable versions, but is here to expose these to JavaScript.
460  Q_INVOKABLE virtual void setParentID(const QUuid& parentID) override;
461 
462  /*@jsdoc
463  * Gets the joint of the entity or avatar that the avatar is parented to.
464  * @function MyAvatar.getParentJointIndex
465  * @returns {number} The joint of the entity or avatar that the avatar is parented to. <code>65535</code> or
466  * <code>-1</code> if parented to the entity or avatar's position and orientation rather than a joint.
467  */
468  // This calls through to the SpatiallyNestable versions, but is here to expose these to JavaScript.
469  Q_INVOKABLE virtual quint16 getParentJointIndex() const override { return SpatiallyNestable::getParentJointIndex(); }
470 
471  /*@jsdoc
472  * Sets the joint of the entity or avatar that the avatar is parented to.
473  * @function MyAvatar.setParentJointIndex
474  * @param {number} parentJointIndex - The joint of the entity or avatar that the avatar should be parented to. Use
475  * <code>65535</code> or <code>-1</code> to parent to the entity or avatar's position and orientation rather than a
476  * joint.
477  */
478  // This calls through to the SpatiallyNestable versions, but is here to expose these to JavaScript.
479  Q_INVOKABLE virtual void setParentJointIndex(quint16 parentJointIndex) override;
480 
481  /*@jsdoc
482  * Gets information on all the joints in the avatar's skeleton.
483  * @function MyAvatar.getSkeleton
484  * @returns {SkeletonJoint[]} Information about each joint in the avatar's skeleton.
485  */
486  Q_INVOKABLE QList<QVariant> getSkeleton();
487 
488  // NOT thread safe, must be called on main thread.
489  glm::vec3 getUncachedLeftPalmPosition() const;
490  glm::quat getUncachedLeftPalmRotation() const;
491  glm::vec3 getUncachedRightPalmPosition() const;
492  glm::quat getUncachedRightPalmRotation() const;
493 
494  uint64_t getLastRenderUpdateTime() const { return _lastRenderUpdateTime; }
495  void setLastRenderUpdateTime(uint64_t time) { _lastRenderUpdateTime = time; }
496 
497  void animateScaleChanges(float deltaTime);
498  void setTargetScale(float targetScale) override;
499  float getTargetScale() const { return _targetScale; }
500 
501  /*@jsdoc
502  * @function MyAvatar.getSimulationRate
503  * @param {AvatarSimulationRate} [rateName=""] - Rate name.
504  * @returns {number} Simulation rate in Hz.
505  * @deprecated This function is deprecated and will be removed.
506  */
507  Q_INVOKABLE float getSimulationRate(const QString& rateName = QString("")) const;
508 
509  bool hasNewJointData() const { return _hasNewJointData; }
510 
511  float getBoundingRadius() const;
512  AABox getRenderBounds() const; // THis call is accessible from rendering thread only to report the bounding box of the avatar during the frame.
513  AABox getFitBounds() const { return _fitBoundingBox; }
514 
515  void addToScene(AvatarSharedPointer self, const render::ScenePointer& scene);
516  void ensureInScene(AvatarSharedPointer self, const render::ScenePointer& scene);
517  bool isInScene() const { return render::Item::isValidID(_renderItemID); }
518  render::ItemID getRenderItemID() { return _renderItemID; }
519  bool isMoving() const { return _moving; }
520 
521  void fadeIn(render::ScenePointer scene);
522  void fadeOut(render::Transaction& transaction, KillAvatarReason reason);
523  render::Transition::Type getLastFadeRequested() 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 signals:
560  /*@jsdoc
561  * Triggered when the avatar's target scale is changed. The target scale is the desired scale of the avatar without any
562  * restrictions on permissible scale values imposed by the domain.
563  * @function MyAvatar.targetScaleChanged
564  * @param {number} targetScale - The avatar's target scale.
565  * @returns Signal
566  */
567  void targetScaleChanged(float targetScale);
568 
569 public slots:
570 
571  // FIXME - these should be migrated to use Pose data instead
572  // thread safe, will return last valid palm from cache
573 
574  /*@jsdoc
575  * Gets the position of the left palm in world coordinates.
576  * @function MyAvatar.getLeftPalmPosition
577  * @returns {Vec3} The position of the left palm in world coordinates.
578  * @example <caption>Report the position of your avatar's left palm.</caption>
579  * print(JSON.stringify(MyAvatar.getLeftPalmPosition()));
580  */
581  glm::vec3 getLeftPalmPosition() const;
582 
583  /*@jsdoc
584  * Gets the rotation of the left palm in world coordinates.
585  * @function MyAvatar.getLeftPalmRotation
586  * @returns {Quat} The rotation of the left palm in world coordinates.
587  * @example <caption>Report the rotation of your avatar's left palm.</caption>
588  * print(JSON.stringify(MyAvatar.getLeftPalmRotation()));
589  */
590  glm::quat getLeftPalmRotation() const;
591 
592  /*@jsdoc
593  * Gets the position of the right palm in world coordinates.
594  * @function MyAvatar.getRightPalmPosition
595  * @returns {Vec3} The position of the right palm in world coordinates.
596  * @example <caption>Report the position of your avatar's right palm.</caption>
597  * print(JSON.stringify(MyAvatar.getRightPalmPosition()));
598  */
599  glm::vec3 getRightPalmPosition() const;
600 
601  /*@jsdoc
602  * Get the rotation of the right palm in world coordinates.
603  * @function MyAvatar.getRightPalmRotation
604  * @returns {Quat} The rotation of the right palm in world coordinates.
605  * @example <caption>Report the rotation of your avatar's right palm.</caption>
606  * print(JSON.stringify(MyAvatar.getRightPalmRotation()));
607  */
608  glm::quat getRightPalmRotation() const;
609 
610  /*@jsdoc
611  * @function MyAvatar.setModelURLFinished
612  * @param {boolean} success
613  * @deprecated This function is deprecated and will be removed.
614  */
615  // hooked up to Model::setURLFinished signal
616  void setModelURLFinished(bool success);
617 
618  /*@jsdoc
619  * @function MyAvatar.rigReady
620  * @deprecated This function is deprecated and will be removed.
621  */
622  // Hooked up to Model::rigReady signal
623  void rigReady();
624 
625  /*@jsdoc
626  * @function MyAvatar.rigReset
627  * @deprecated This function is deprecated and will be removed.
628  */
629  // Hooked up to Model::rigReset signal
630  void rigReset();
631 
632 protected:
633  float getUnscaledEyeHeightFromSkeleton() const;
634  void buildUnscaledEyeHeightCache();
635  void buildSpine2SplineRatioCache();
636  void clearUnscaledEyeHeightCache();
637  void clearSpine2SplineRatioCache();
638  virtual const QString& getSessionDisplayNameForTransport() const override { return _empty; } // Save a tiny bit of bandwidth. Mixer won't look at what we send.
639  QString _empty{};
640  virtual void maybeUpdateSessionDisplayNameFromTransport(const QString& sessionDisplayName) override { _sessionDisplayName = sessionDisplayName; } // don't use no-op setter!
641  void computeMultiSphereShapes();
642  void updateFitBoundingBox();
643 
644  SkeletonModelPointer _skeletonModel;
645 
646  void invalidateJointIndicesCache() const;
647  void withValidJointIndicesCache(std::function<void()> const& worker) const;
648  mutable QHash<QString, int> _modelJointIndicesCache;
649  mutable QReadWriteLock _modelJointIndicesCacheLock;
650  mutable bool _modelJointsCached { false };
651 
652  glm::vec3 _skeletonOffset;
653  std::vector<std::shared_ptr<Model>> _attachmentModels;
654  std::vector<bool> _attachmentModelsTexturesLoaded;
655  std::vector<std::shared_ptr<Model>> _attachmentsToRemove;
656  std::vector<std::shared_ptr<Model>> _attachmentsToDelete;
657 
658  float _bodyYawDelta { 0.0f }; // degrees/sec
659  float _seatedBodyYawDelta{ 0.0f }; // degrees/renderframe
660 
661  // These position histories and derivatives are in the world-frame.
662  // The derivatives are the MEASURED results of all external and internal forces
663  // and are therefore READ-ONLY --> motion control of the Avatar is NOT obtained
664  // by setting these values.
665  // Floating point error prevents us from accurately measuring velocity using a naive approach
666  // (e.g. vel = (pos - lastPos)/dt) so instead we use _positionDeltaAccumulator.
667  glm::vec3 _positionDeltaAccumulator;
668  glm::vec3 _lastVelocity;
669  glm::vec3 _acceleration;
670  glm::vec3 _angularVelocity;
671  glm::vec3 _lastAngularVelocity;
672  glm::vec3 _angularAcceleration;
673  glm::quat _lastOrientation;
674  glm::vec3 _worldUpDirection { Vectors::UP };
675  bool _moving { false };
676 
677  // protected methods...
678  bool isLookingAtMe(AvatarSharedPointer avatar) const;
679  virtual void sendPacket(const QUuid& entityID) const { }
680  bool applyGrabChanges();
681  void relayJointDataToChildren();
682 
683  void fade(render::Transaction& transaction, render::Transition::Type type);
684 
685  glm::vec3 getBodyRightDirection() const { return getWorldOrientation() * IDENTITY_RIGHT; }
686  glm::vec3 getBodyUpDirection() const { return getWorldOrientation() * IDENTITY_UP; }
687  void measureMotionDerivatives(float deltaTime);
688  bool getCollideWithOtherAvatars() const { return _collideWithOtherAvatars; }
689 
690  float getSkeletonHeight() const;
691  float getHeadHeight() const;
692  float getPelvisFloatingHeight() const;
693  glm::vec3 getDisplayNamePosition() const;
694 
695  Transform calculateDisplayNameTransform(const ViewFrustum& view, const glm::vec3& textPosition) const;
696  void renderDisplayName(gpu::Batch& batch, const ViewFrustum& view, const glm::vec3& textPosition, bool forward) const;
697  virtual bool shouldRenderHead(const RenderArgs* renderArgs) const;
698  virtual void fixupModelsInScene(const render::ScenePointer& scene);
699 
700  virtual void updatePalms();
701 
702  render::ItemID _renderItemID{ render::Item::INVALID_ITEM_ID };
703  render::Transition::Type _lastFadeRequested { render::Transition::Type::NONE }; // Used for sanity checking
704 
705  ThreadSafeValueCache<glm::vec3> _leftPalmPositionCache { glm::vec3() };
706  ThreadSafeValueCache<glm::quat> _leftPalmRotationCache { glm::quat() };
707  ThreadSafeValueCache<glm::vec3> _rightPalmPositionCache { glm::vec3() };
708  ThreadSafeValueCache<glm::quat> _rightPalmRotationCache { glm::quat() };
709 
710  // Some rate tracking support
711  RateCounter<> _simulationRate;
712  RateCounter<> _simulationInViewRate;
713  RateCounter<> _skeletonModelSimulationRate;
714  RateCounter<> _jointDataSimulationRate;
715 
716  class AvatarEntityDataHash {
717  public:
718  AvatarEntityDataHash(uint32_t h) : hash(h) {};
719  uint32_t hash { 0 };
720  bool success { false };
721  };
722 
723  uint64_t _lastRenderUpdateTime { 0 };
724  int _leftPointerGeometryID { 0 };
725  int _rightPointerGeometryID { 0 };
726  int _nameRectGeometryID { 0 };
727  bool _initialized { false };
728  bool _isAnimatingScale { false };
729  bool _mustFadeIn { false };
730  bool _reconstructSoftEntitiesJointMap { false };
731  float _modelScale { 1.0f };
732 
733  AvatarTransit _transit;
734  std::mutex _transitLock;
735 
736  int _voiceSphereID;
737 
738  float _displayNameTargetAlpha { 1.0f };
739  float _displayNameAlpha { 1.0f };
740 
741  ThreadSafeValueCache<float> _unscaledEyeHeightCache { DEFAULT_AVATAR_EYE_HEIGHT };
742  float _spine2SplineRatio { DEFAULT_SPINE2_SPLINE_PROPORTION };
743  glm::vec3 _spine2SplineOffset;
744 
745  std::unordered_map<std::string, graphics::MultiMaterial> _materials;
746  std::mutex _materialsLock;
747 
748  void processMaterials();
749 
750  AABox _renderBound;
751  bool _isMeshVisible{ true };
752  bool _needMeshVisibleSwitch{ true };
753 
754  static const float MYAVATAR_LOADING_PRIORITY;
755  static const float OTHERAVATAR_LOADING_PRIORITY;
756  static const float ATTACHMENT_LOADING_PRIORITY;
757 
758  LoadingStatus _loadingStatus { LoadingStatus::NoModel };
759 
760  static void metaBlendshapeOperator(render::ItemID renderItemID, int blendshapeNumber, const QVector<BlendshapeOffset>& blendshapeOffsets,
761  const QVector<int>& blendedMeshSizes, const render::ItemIDs& subItemIDs);
762 
763  std::vector<MultiSphereShape> _multiSphereShapes;
764  AABox _fitBoundingBox;
765  void clearAvatarGrabData(const QUuid& grabID) override;
766 
767  using SetOfIDs = std::set<QUuid>;
768  using VectorOfIDs = std::vector<QUuid>;
769  using MapOfGrabs = std::map<QUuid, GrabPointer>;
770 
771  MapOfGrabs _avatarGrabs;
772  SetOfIDs _grabsToChange; // updated grab IDs -- changes needed to entities or physics
773  VectorOfIDs _grabsToDelete; // deleted grab IDs -- changes needed to entities or physics
774 
775  ReadWriteLockable _subItemLock;
776  void updateAttachmentRenderIDs();
777  render::ItemIDs _attachmentRenderIDs;
778  void updateDescendantRenderIDs();
779  render::ItemIDs _descendantRenderIDs;
780  std::unordered_set<EntityItemID> _renderingDescendantEntityIDs;
781  uint32_t _lastAncestorChainRenderableVersion { 0 };
782 };
783 
784 #endif // hifi_Avatar_h
A simple object wrapper for an OpenGL texture.
Definition: material-networking/src/material-networking/TextureCache.h:39