MeshPrimitive2.h 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360
  1. #ifndef GUL_MESH_PRIMITIVE_2_H
  2. #define GUL_MESH_PRIMITIVE_2_H
  3. #include <cmath>
  4. #include <vector>
  5. #include <array>
  6. #include <cstring>
  7. #include <tuple>
  8. #include <string>
  9. #include <fstream>
  10. #include <sstream>
  11. #include <cassert>
  12. #include <map>
  13. namespace gul
  14. {
  15. enum class eComponentType : uint32_t
  16. {
  17. UNKNOWN = 0,
  18. BYTE = 5120,
  19. UNSIGNED_BYTE = 5121,
  20. SHORT = 5122,
  21. UNSIGNED_SHORT = 5123,
  22. INT = 5124,
  23. UNSIGNED_INT = 5125,
  24. FLOAT = 5126,
  25. DOUBLE = 5130
  26. };
  27. enum class eType : uint32_t
  28. {
  29. // rows columns
  30. UNKNOWN = 0x00000000 | 0x00000000,
  31. SCALAR = 0x00000100 | 0x00000001,
  32. VEC2 = 0x00000100 | 0x00000002,
  33. VEC3 = 0x00000100 | 0x00000003,
  34. VEC4 = 0x00000100 | 0x00000004,
  35. MAT2 = 0x00000200 | 0x00000002,
  36. MAT3 = 0x00000300 | 0x00000003,
  37. MAT4 = 0x00000400 | 0x00000004
  38. };
  39. constexpr const char* to_string(eComponentType t)
  40. {
  41. switch(t)
  42. {
  43. default:
  44. case eComponentType::UNKNOWN : return "UNKNOWN";
  45. case eComponentType::BYTE : return "BYTE";
  46. case eComponentType::UNSIGNED_BYTE : return "UNSIGNED_BYTE";
  47. case eComponentType::SHORT : return "SHORT";
  48. case eComponentType::UNSIGNED_SHORT: return "UNSIGNED_SHORT";
  49. case eComponentType::INT : return "INT";
  50. case eComponentType::UNSIGNED_INT : return "UNSIGNED_INT";
  51. case eComponentType::FLOAT : return "FLOAT";
  52. case eComponentType::DOUBLE : return "DOUBLE";
  53. }
  54. }
  55. constexpr const char* to_string(eType t)
  56. {
  57. switch(t)
  58. {
  59. default:
  60. case eType::UNKNOWN: return "UNKNOWN";
  61. case eType::SCALAR : return "SCALAR";
  62. case eType::VEC2 : return "VEC2";
  63. case eType::VEC3 : return "VEC3";
  64. case eType::VEC4 : return "VEC4";
  65. case eType::MAT2 : return "MAT2";
  66. case eType::MAT3 : return "MAT3";
  67. case eType::MAT4 : return "MAT4";
  68. }
  69. }
  70. /**
  71. * @brief row_type
  72. * @param c
  73. * @return
  74. *
  75. * Returns the row type
  76. */
  77. constexpr eType row_type(eType c)
  78. {
  79. switch ( c )
  80. {
  81. case eType::UNKNOWN: return eType::UNKNOWN;
  82. case eType::SCALAR : return eType::UNKNOWN;
  83. case eType::VEC2 : return eType::SCALAR;
  84. case eType::VEC3 : return eType::SCALAR;
  85. case eType::VEC4 : return eType::SCALAR;
  86. case eType::MAT2 : return eType::VEC2;
  87. case eType::MAT3 : return eType::VEC3;
  88. case eType::MAT4 : return eType::VEC4;
  89. }
  90. return eType::UNKNOWN;
  91. }
  92. constexpr uint32_t component_row_count(eType c)
  93. {
  94. return (static_cast<uint32_t>(c) & 0x000000FF);
  95. }
  96. constexpr uint32_t component_column_count(eType c)
  97. {
  98. return ( (static_cast<uint32_t>(c) >> 8) & 0x000000FF);
  99. }
  100. constexpr uint32_t component_count(eType c)
  101. {
  102. return component_row_count(c) * component_column_count(c);
  103. }
  104. constexpr uint32_t component_size(eComponentType c)
  105. {
  106. switch(c)
  107. {
  108. case gul::eComponentType::BYTE:
  109. case gul::eComponentType::UNSIGNED_BYTE: return 1;
  110. case gul::eComponentType::SHORT:
  111. case gul::eComponentType::UNSIGNED_SHORT: return 2;
  112. case gul::eComponentType::INT:
  113. case gul::eComponentType::UNSIGNED_INT:
  114. case gul::eComponentType::FLOAT: return 4;
  115. case gul::eComponentType::DOUBLE: return 8;
  116. default:
  117. return 0;
  118. }
  119. }
  120. /**
  121. * @brief type_to_component
  122. * @return
  123. *
  124. * Given a datatype, either fundamental, array<T>, or glm type
  125. * return the base component type. If it is non-fundamental type
  126. * T::value_type must exist
  127. */
  128. template<typename T>
  129. constexpr eComponentType type_to_component()
  130. {
  131. if constexpr ( std::is_arithmetic_v<T> )
  132. {
  133. if constexpr (std::is_same_v<T, int8_t>) return eComponentType::BYTE;
  134. else if constexpr (std::is_same_v<T, uint8_t>) return eComponentType::UNSIGNED_BYTE;
  135. else if constexpr (std::is_same_v<T, int16_t>) return eComponentType::SHORT;
  136. else if constexpr (std::is_same_v<T, uint16_t>) return eComponentType::UNSIGNED_SHORT;
  137. else if constexpr (std::is_same_v<T, int32_t>) return eComponentType::INT;
  138. else if constexpr (std::is_same_v<T, uint32_t>) return eComponentType::UNSIGNED_INT;
  139. else if constexpr (std::is_same_v<T, float>) return eComponentType::FLOAT;
  140. else if constexpr (std::is_same_v<T, double>) return eComponentType::DOUBLE;
  141. else
  142. {
  143. return eComponentType::UNKNOWN;
  144. }
  145. }
  146. else
  147. {
  148. return type_to_component<typename T::value_type>();
  149. }
  150. }
  151. /**
  152. * @brief type_to_type
  153. * @return
  154. *
  155. * Converts a C++ datatype into a eType
  156. */
  157. template<typename T>
  158. constexpr eType type_to_type()
  159. {
  160. if constexpr ( std::is_arithmetic_v<T>) // integer or float types
  161. {
  162. return eType::SCALAR;
  163. }
  164. else
  165. {
  166. constexpr auto component = type_to_component<T>();
  167. constexpr auto size = component_size(component);
  168. constexpr auto componentCount = sizeof(T) / size;
  169. static_assert(componentCount == 1 ||
  170. componentCount == 2 ||
  171. componentCount == 3 ||
  172. componentCount == 4 ||
  173. componentCount == 9 ||
  174. componentCount == 16);
  175. if constexpr ( componentCount == 4 )
  176. {
  177. // either a vec4 or a mat2
  178. // so we need to determine whether V[0] is an arithmetic type
  179. // or a
  180. struct S
  181. {
  182. auto operator()()
  183. {
  184. return T()[0];
  185. }
  186. };
  187. //std::invoke_result
  188. if constexpr( std::is_arithmetic_v< typename std::invoke_result<S>::type> )
  189. {
  190. // T[0] is arithmetic so its vec4
  191. return eType::VEC4;
  192. }
  193. else
  194. {
  195. // T[0] is likely a vec[2] so its a matrix
  196. return eType::MAT2;
  197. }
  198. }
  199. else
  200. {
  201. // in all other cases we can determine the type by the total number
  202. // of components
  203. switch ( sizeof(T) / size)
  204. {
  205. case 1:
  206. return eType::SCALAR;
  207. case 2:
  208. return eType::VEC2;
  209. case 3:
  210. return eType::VEC3;
  211. case 4:
  212. return eType::VEC4;
  213. case 9:
  214. return eType::MAT3;
  215. case 16:
  216. return eType::MAT4;
  217. default:
  218. return eType::UNKNOWN;
  219. }
  220. }
  221. }
  222. }
  223. /**
  224. * @brief The VertexAttribute struct
  225. *
  226. * The vertex attribute class is essentially a vector of data
  227. * for a single attribute. This is NOT meant for compound vertices: eg
  228. * struct Vertex
  229. * {
  230. * vec3 position;
  231. * vec2 uv;
  232. * }
  233. *
  234. *
  235. */
  236. struct VertexAttribute
  237. {
  238. VertexAttribute()
  239. {
  240. }
  241. VertexAttribute(eComponentType c, eType t)
  242. {
  243. m_componentType = c;
  244. m_type = t;
  245. }
  246. template<typename T>
  247. VertexAttribute( std::vector<T> const & V)
  248. {
  249. using container_type = std::decay_t<decltype(V) >;
  250. using attribute_type = typename container_type::value_type;
  251. m_componentType = type_to_component<attribute_type>();
  252. m_type = type_to_type<attribute_type>();
  253. m_data.resize( getAttributeSize() * V.size() );
  254. std::memcpy(m_data.data(), V.data(), m_data.size());
  255. }
  256. void dump(std::ostream & out, std::string name)
  257. {
  258. out.write(name.data(), static_cast<std::streamsize>(name.size()));
  259. out.write(reinterpret_cast<const char*>(&m_componentType), sizeof(m_componentType));
  260. out.write(reinterpret_cast<const char*>(&m_type), sizeof(m_type));
  261. out.write(reinterpret_cast<const char*>(m_data.data()), static_cast<std::streamsize>(m_data.size()));
  262. }
  263. /**
  264. * @brief init
  265. * @param c
  266. * @param t
  267. *
  268. * Initialize the vertex attribute based on its base component type and
  269. * its attribute type
  270. */
  271. void init(eComponentType c, eType t)
  272. {
  273. m_componentType = c;
  274. m_type = t;
  275. }
  276. template<typename T>
  277. VertexAttribute& operator=(std::vector<T> const & V)
  278. {
  279. using container_type = std::decay_t<decltype(V) >;
  280. using attribute_type = typename container_type::value_type;
  281. m_componentType = type_to_component<attribute_type>();
  282. m_type = type_to_type<attribute_type>();
  283. m_data.resize( getAttributeSize() * V.size() );
  284. std::memcpy(m_data.data(), V.data(), m_data.size());
  285. return *this;
  286. }
  287. template<typename T>
  288. std::vector<T> toVector() const
  289. {
  290. std::vector<T> data( m_data.size() / sizeof(T));
  291. std::memcpy(data.data(), m_data.data(), sizeof(T)*data.size());
  292. return data;
  293. }
  294. /**
  295. * @brief at
  296. * @param i
  297. * @return
  298. *
  299. * Returns the value of a component
  300. */
  301. template<typename T>
  302. T at(size_t index, size_t componentIndex=0) const
  303. {
  304. T v;
  305. std::memcpy(&v, m_data.data() + index * getAttributeSize() + componentIndex * component_size(m_componentType), sizeof(T));
  306. return v;
  307. }
  308. /**
  309. * @brief get
  310. * @param index
  311. * @return
  312. *
  313. * Treats the VertexAttribute as a vector<T> and returns
  314. * the index into that vector
  315. */
  316. template<typename T>
  317. T get(size_t index) const
  318. {
  319. T v;
  320. std::memcpy(&v, m_data.data() + index * sizeof(T), sizeof(T));
  321. return v;
  322. }
  323. /**
  324. * @brief getAttributeAs
  325. * @param index
  326. * @return
  327. *
  328. * different from get(), return's the attribute specified by index,
  329. * the a
  330. */
  331. template<typename T>
  332. T getAttributeAs(size_t index) const
  333. {
  334. T v;
  335. std::memcpy(&v, m_data.data() + index * getAttributeSize(), sizeof(T));
  336. return v;
  337. }
  338. /**
  339. * @brief set
  340. * @param index
  341. * @param v
  342. *
  343. * Treats the VertexAttribute as a vector<T> and sets
  344. * vertexAttribute[index] = v
  345. */
  346. template<typename T>
  347. void set(size_t index, T const &v)
  348. {
  349. std::memcpy(m_data.data() + index*sizeof(T), &v, sizeof(T));
  350. }
  351. /**
  352. * @brief size
  353. * @return
  354. *
  355. * Returns the total number of components in the attribute array.
  356. *
  357. * If ther are 4 vertices and each vertex has xyz components, the
  358. * return value will be 12
  359. */
  360. size_t size() const
  361. {
  362. return attributeCount() * getNumComponents();
  363. }
  364. /**
  365. * @brief push_back
  366. * @param v
  367. *
  368. * Pushes data to the end of the vector
  369. */
  370. template<typename T>
  371. void push_back(T const & v)
  372. {
  373. appendData(&v, sizeof(v));
  374. }
  375. void appendData(void const *data, size_t byteCount)
  376. {
  377. auto m = m_data.size();
  378. m_data.resize(m + byteCount);
  379. std::memcpy( &m_data[m], data, byteCount);
  380. }
  381. void reserveBytes(size_t byteCount)
  382. {
  383. m_data.reserve(byteCount);
  384. }
  385. bool empty() const
  386. {
  387. return m_data.empty();
  388. }
  389. /**
  390. * @brief getType
  391. * @return
  392. *
  393. */
  394. eType getType() const
  395. {
  396. return m_type;
  397. }
  398. eComponentType getComponentType() const
  399. {
  400. return m_componentType;
  401. }
  402. uint32_t getNumComponents() const
  403. {
  404. return component_count(m_type);
  405. }
  406. std::array<uint32_t,2> getShape() const
  407. {
  408. return { static_cast<uint32_t>(attributeCount()), getNumComponents()};
  409. }
  410. /**
  411. * @brief convertTo32BitInteger
  412. *
  413. * Used only for uint and ints. Converts a lower
  414. * bit value into the 32 bit equivelant
  415. */
  416. bool convertTo32BitInteger()
  417. {
  418. auto totalComponents = attributeCount() * getNumComponents();
  419. if(getComponentType() == eComponentType::UNSIGNED_BYTE)
  420. {
  421. VertexAttribute newData(eComponentType::UNSIGNED_INT, getType());
  422. for(uint32_t i=0;i<totalComponents;i++)
  423. {
  424. newData.push_back<uint32_t>(get<uint8_t>(i));
  425. }
  426. *this = std::move(newData);
  427. return true;
  428. }
  429. if(getComponentType() == eComponentType::UNSIGNED_SHORT)
  430. {
  431. VertexAttribute newData(eComponentType::UNSIGNED_INT, getType());
  432. for(uint32_t i=0;i<totalComponents;i++)
  433. {
  434. newData.push_back<uint32_t>(get<uint16_t>(i));
  435. }
  436. *this = std::move(newData);
  437. return true;
  438. }
  439. if(getComponentType() == eComponentType::BYTE)
  440. {
  441. VertexAttribute newData(eComponentType::INT, getType());
  442. for(uint32_t i=0;i<totalComponents;i++)
  443. {
  444. newData.push_back<int32_t>(get<int8_t>(i));
  445. }
  446. *this = std::move(newData);
  447. return true;
  448. }
  449. if(getComponentType() == eComponentType::SHORT)
  450. {
  451. VertexAttribute newData(eComponentType::INT, getType());
  452. for(uint32_t i=0;i<totalComponents;i++)
  453. {
  454. newData.push_back<int32_t>(get<int16_t>(i));
  455. }
  456. *this = std::move(newData);
  457. return true;
  458. }
  459. return false;
  460. }
  461. void* data()
  462. {
  463. return m_data.data();
  464. }
  465. void const* data() const
  466. {
  467. return m_data.data();
  468. }
  469. /**
  470. * @brief getAttributeSize
  471. * @return
  472. *
  473. * Returns the size of the attribute. If it returns 0 it means that
  474. * the attribute type has not been set
  475. */
  476. uint32_t getAttributeSize() const
  477. {
  478. return component_size(m_componentType) * component_count(m_type);
  479. }
  480. uint64_t getByteSize() const
  481. {
  482. return m_data.size();
  483. }
  484. /**
  485. * @brief attributeCount
  486. * @return
  487. *
  488. * Returns the total number of attributes in the buffer.
  489. */
  490. uint64_t attributeCount() const
  491. {
  492. auto s = getAttributeSize();
  493. return s == 0 ? 0 : m_data.size() / s;
  494. }
  495. /**
  496. * @brief resize
  497. * @param attrCount
  498. *
  499. * Resize the attribute vector to be able to hold attrCount attributes
  500. */
  501. void resize(size_t attrCount)
  502. {
  503. m_data.resize( attrCount * getAttributeSize() );
  504. }
  505. /**
  506. * @brief canMerge
  507. * @param B
  508. * @return
  509. *
  510. * Returns wither you can merge this vertex attribute with another.
  511. * You can only merge the two if the componentType and the Type are the same
  512. */
  513. bool canMerge(VertexAttribute const & B) const
  514. {
  515. return m_componentType == B.m_componentType && m_type == B.m_type;
  516. }
  517. /**
  518. * @brief merge
  519. * @param B
  520. * @return
  521. *
  522. * Merge B to the end of the attribute vector and return the byte offset
  523. * at which the data was merged.
  524. */
  525. uint64_t merge(VertexAttribute const& B)
  526. {
  527. auto s = m_data.size();
  528. m_data.insert(m_data.end(), B.m_data.begin(), B.m_data.end());
  529. return s;
  530. }
  531. /**
  532. * @brief strideCopy
  533. * @param data
  534. * @param stride
  535. *
  536. * Copy the vertex attribute data into the memory location.
  537. *
  538. * if V = [p0,p1,p2,p3]
  539. *
  540. * Then a stride copy of strideCopy(data, 2*sizeof(p0)) will copy data as follows
  541. *
  542. * data = [p0| |p1| |p2| |p3]
  543. *
  544. * This is used to interleave multiple attribute. eg:
  545. *
  546. * positionAttribute.strideCopy(data, sizeof(vec3) )
  547. * uvAttribute.strideCopy( data+sizeof(vec3), sizeof(vec2) )
  548. */
  549. void strideCopy(void * data, uint64_t stride) const
  550. {
  551. auto c = attributeCount();
  552. auto s = getAttributeSize();
  553. auto d_in = static_cast<uint8_t const*>(m_data.data());
  554. auto d_out = static_cast<uint8_t*>(data);
  555. for(uint64_t i=0;i<c;i++)
  556. {
  557. std::memcpy(d_out, d_in, s);
  558. d_out += stride;
  559. d_in += s;
  560. }
  561. }
  562. /**
  563. * @brief strideCopyOffset
  564. * @param dstData - the start of the destination to copy to
  565. * @param dstByteStride - how many bytes to skip after copying each attribute
  566. * @param dstByteOffset - the offset from the start of dstData to start copying to
  567. *
  568. * @param srcStartAttributeIndex - which index in the source attribute to start copying from
  569. * @param attributeCountToCopy - number of attributes to copy
  570. * @return
  571. *
  572. * Copies the attribute data to dstData+dstByteOffset
  573. */
  574. uint64_t strideCopyOffset(void * dstData,
  575. uint64_t dstByteStride,
  576. uint64_t dstByteOffset,
  577. uint64_t srcStartAttributeIndex,
  578. uint64_t attributeCountToCopy = std::numeric_limits<uint64_t>::max()) const
  579. {
  580. auto c = std::min(attributeCount(), attributeCountToCopy);
  581. auto srcAttrSize = getAttributeSize();
  582. auto d_in = static_cast<uint8_t const*>(m_data.data()) + srcStartAttributeIndex * srcAttrSize;
  583. auto d_in_end = std::min(d_in + srcAttrSize * attributeCountToCopy, &m_data.back()+1);
  584. auto d_out = static_cast<uint8_t*>(dstData) + dstByteOffset;
  585. while(d_in < d_in_end)
  586. {
  587. std::memcpy(d_out, d_in, srcAttrSize);
  588. d_out += dstByteStride;
  589. d_in += srcAttrSize;
  590. }
  591. return c;
  592. }
  593. /**
  594. * @brief strideCopy
  595. * @param data
  596. * @param n
  597. * @param offset
  598. * @param stride
  599. * @param num
  600. *
  601. * Copies num attributes into memory starting at data+offset with a specific stride.
  602. *
  603. * For example
  604. *
  605. * <-offset-> <--stride-->
  606. * [ | A1 | | A2 | | A3 | ]
  607. * ^--data
  608. */
  609. [[deprecated]] uint64_t strideCopy(void * data, uint64_t stride, uint64_t offset, uint64_t num = std::numeric_limits<uint64_t>::max()) const
  610. {
  611. auto c = std::min(attributeCount(), num);
  612. auto s = getAttributeSize();
  613. auto d_in = static_cast<uint8_t const*>(m_data.data());
  614. auto d_out = static_cast<uint8_t*>(data)+offset;
  615. for(uint64_t i=0;i<c;i++)
  616. {
  617. std::memcpy(d_out, d_in, s);
  618. d_out += stride;
  619. d_in += s;
  620. }
  621. return c;
  622. }
  623. void clear()
  624. {
  625. m_data.clear();
  626. }
  627. void setType(eType t)
  628. {
  629. m_type = t;
  630. }
  631. void setComponent(eComponentType c)
  632. {
  633. m_componentType = c;
  634. }
  635. /**
  636. * @brief getMinMax
  637. * @return
  638. *
  639. * Returns the min and max values for each component.
  640. */
  641. template<typename T>
  642. std::pair< std::vector<T>, std::vector<T>> getMinMax() const
  643. {
  644. auto & V = *this;
  645. static_assert( std::is_arithmetic_v<T>, "T must be an arithmetic type");
  646. using value_type = T;
  647. std::vector<value_type> _min(component_count(V.getType()), std::numeric_limits<value_type>::max() );
  648. std::vector<value_type> _max(component_count(V.getType()), std::numeric_limits<value_type>::lowest() );
  649. auto attrCount = attributeCount();
  650. for(uint32_t j=0;j<attrCount;j++)
  651. {
  652. for(size_t i=0;i<_min.size();i++)
  653. {
  654. _min[i] = std::min( V.at<value_type>(j, i), _min[i] );
  655. _max[i] = std::max( V.at<value_type>(j, i), _max[i] );
  656. }
  657. }
  658. return {_min, _max};
  659. }
  660. protected:
  661. friend struct MeshPrimitive;
  662. std::vector<uint8_t> m_data;
  663. eComponentType m_componentType = eComponentType::UNKNOWN;
  664. eType m_type = eType::UNKNOWN;
  665. };
  666. /**
  667. * @brief fromGLTFAccessor
  668. * @param startOfBufferView
  669. * @param bufferViewByteStride
  670. * @param accessorCount
  671. * @param accessorByteOffset
  672. * @param accessorComponentType
  673. * @param accessorType
  674. * @return
  675. *
  676. * When reading a GLTF asset, a single mesh vertex attribute is defined
  677. * in an accessor/bufferView.
  678. *
  679. * Given the accessor/bufferView information in the JSON file, this
  680. * function will read the bytes from the raw bufferView data and return
  681. * a single VertexAttribute
  682. */
  683. inline VertexAttribute fromGLTFAccessor(void const *startOfBufferView,
  684. uint32_t bufferViewByteStride,
  685. uint32_t accessorCount,
  686. uint32_t accessorByteOffset,
  687. uint32_t accessorComponentType,
  688. std::string accessorType)
  689. {
  690. VertexAttribute V;
  691. uint32_t accessorSize = component_size(static_cast<eComponentType>(accessorComponentType));
  692. assert(accessorSize != 0);
  693. V.setComponent(static_cast<eComponentType>(accessorComponentType));
  694. if(accessorType == "SCALAR") { V.setType(eType::SCALAR); accessorSize *= 1; }
  695. else if(accessorType == "VEC2") { V.setType(eType::VEC2); accessorSize *= 2; }
  696. else if(accessorType == "VEC3") { V.setType(eType::VEC3); accessorSize *= 3; }
  697. else if(accessorType == "VEC4") { V.setType(eType::VEC4); accessorSize *= 4; }
  698. else if(accessorType == "MAT2") { V.setType(eType::MAT2); accessorSize *= 4; }
  699. else if(accessorType == "MAT3") { V.setType(eType::MAT3); accessorSize *= 9; }
  700. else if(accessorType == "MAT4") { V.setType(eType::MAT4); accessorSize *= 16;}
  701. V.reserveBytes( accessorCount * accessorSize );
  702. if(bufferViewByteStride == 0)
  703. {
  704. bufferViewByteStride = accessorSize;
  705. }
  706. auto _read = static_cast<uint8_t const*>(startOfBufferView) + accessorByteOffset;
  707. for(uint32_t i=0;i<accessorCount;i++)
  708. {
  709. V.appendData(_read, accessorSize);
  710. std::advance(_read, bufferViewByteStride);
  711. }
  712. return V;
  713. }
  714. //===========================================================================================================
  715. /**
  716. * @brief calculateInterleavedStride
  717. * @param attrs
  718. * @return
  719. *
  720. * Calculates the sum of each attr[i].attributeSize() skipping any attributes that dont have
  721. * items
  722. */
  723. inline uint64_t calculateInterleavedStride(std::vector<VertexAttribute const*> const &attrs)
  724. {
  725. uint64_t stride=0;
  726. for(auto * v : attrs)
  727. {
  728. if(v->size() > 0)
  729. stride += v->getAttributeSize();
  730. }
  731. return stride;
  732. }
  733. /**
  734. * @brief calculateInterleavedBytes
  735. * @param attrs
  736. * @return
  737. *
  738. * Returns the total number of bytes required to store all attributes in
  739. * interleaved format, attributes with zero attributeCount() are not included
  740. */
  741. inline uint64_t calculateInterleavedBytes(std::vector<VertexAttribute const*> const &attrs)
  742. {
  743. auto stride = calculateInterleavedStride(attrs);
  744. uint64_t vCount = 9999999999999;
  745. for(auto * v : attrs)
  746. {
  747. if(v->size() > 0)
  748. vCount = std::min(vCount,v->attributeCount());
  749. }
  750. return stride*vCount;
  751. }
  752. //===========================================================================================================
  753. enum class Topology
  754. {
  755. POINT_LIST = 0,
  756. LINE_LIST = 1,
  757. LINE_STRIP = 2,
  758. TRIANGLE_LIST = 3,
  759. TRIANGLE_STRIP = 4,
  760. TRIANGLE_FAN = 5,
  761. LINE_LIST_WITH_ADJACENCY = 6,
  762. LINE_STRIP_WITH_ADJACENCY = 7,
  763. TRIANGLE_LIST_WITH_ADJACENCY = 8,
  764. TRIANGLE_STRIP_WITH_ADJACENCY = 9,
  765. PATCH_LIST = 10,
  766. };
  767. struct DrawCall
  768. {
  769. uint32_t indexCount = 0;
  770. uint32_t vertexCount = 0;
  771. int32_t vertexOffset = 0;
  772. int32_t indexOffset = 0;
  773. Topology topology = Topology::TRIANGLE_LIST;
  774. };
  775. using SubMesh = DrawCall;
  776. /**
  777. * @brief forEachVertexIndex
  778. * @param _INDEX
  779. * @param p
  780. * @param C
  781. *
  782. * Given an index buffer and a primitive, call the callable, C for each VertexIndex in the primitive.
  783. *
  784. */
  785. template<typename Callable_t>
  786. inline void forEachVertexIndex(VertexAttribute const & _INDEX, SubMesh const & p, Callable_t && C)
  787. {
  788. if( _INDEX.getComponentType() == eComponentType::UNSIGNED_INT)
  789. {
  790. uint32_t vertexOffset = static_cast<uint32_t>(p.vertexOffset);
  791. using IndexComponentType = uint32_t;
  792. for(uint32_t i=0;i < p.indexCount ; i++)
  793. {
  794. uint32_t vertexIndex = _INDEX.at<IndexComponentType>(i + static_cast<uint32_t>(p.indexOffset))
  795. + vertexOffset;
  796. C(vertexIndex);
  797. }
  798. }
  799. }
  800. /**
  801. * @brief The MeshPrimitive struct
  802. *
  803. * A Mesh Primitive is a class which allows
  804. * you to represent a triangular mesh
  805. *
  806. */
  807. struct MeshPrimitive
  808. {
  809. using attribute_type = VertexAttribute;
  810. // list of common attributes in the order specified by the GLTF specification
  811. // initialized using the most common types
  812. attribute_type POSITION = attribute_type(eComponentType::FLOAT, eType::VEC3);
  813. attribute_type NORMAL = attribute_type(eComponentType::FLOAT, eType::VEC3);
  814. attribute_type TANGENT = attribute_type(eComponentType::FLOAT, eType::VEC4);
  815. attribute_type TEXCOORD_0 = attribute_type(eComponentType::FLOAT, eType::VEC2);
  816. attribute_type TEXCOORD_1 = attribute_type(eComponentType::FLOAT, eType::VEC2);
  817. attribute_type COLOR_0 = attribute_type(eComponentType::UNSIGNED_BYTE, eType::VEC4);
  818. attribute_type JOINTS_0 = attribute_type(eComponentType::UNSIGNED_SHORT, eType::VEC4);
  819. attribute_type WEIGHTS_0 = attribute_type(eComponentType::FLOAT, eType::VEC4);
  820. // The index buffer
  821. attribute_type INDEX = attribute_type(eComponentType::UNSIGNED_INT, eType::SCALAR);
  822. Topology topology = Topology::TRIANGLE_LIST;
  823. // a vector of primitives
  824. // each primitive is a sub component of the mesh and
  825. // contains the draw call to draw it
  826. std::vector<SubMesh> primitives;
  827. void clear()
  828. {
  829. for(auto * attr : {&POSITION ,
  830. &NORMAL ,
  831. &TANGENT ,
  832. &TEXCOORD_0,
  833. &TEXCOORD_1,
  834. &COLOR_0 ,
  835. &JOINTS_0 ,
  836. &WEIGHTS_0 ,
  837. &INDEX})
  838. {
  839. attr->clear();
  840. }
  841. }
  842. /**
  843. * @brief dump
  844. * @param out
  845. *
  846. * [experimental]
  847. * Dump the entire mesh to a simple binary file
  848. */
  849. void dump(std::ostream & out)
  850. {
  851. auto attrs = {&POSITION ,
  852. &NORMAL ,
  853. &TANGENT ,
  854. &TEXCOORD_0,
  855. &TEXCOORD_1,
  856. &COLOR_0 ,
  857. &JOINTS_0 ,
  858. &WEIGHTS_0 ,
  859. &INDEX};
  860. struct header_t
  861. {
  862. uint64_t magic = 5496876546618;
  863. uint32_t byteSize=0;
  864. uint32_t numAttributes=0;
  865. };
  866. header_t h;
  867. h.byteSize = 0;
  868. for(auto * attr : attrs)
  869. {
  870. if(attr->size())
  871. {
  872. h.numAttributes++;
  873. }
  874. }
  875. #define DUMP_ATTR(NAME ) if(NAME.size() > 0) NAME.dump(out, #NAME)
  876. out.write(reinterpret_cast<char const *>(&h), sizeof(h));
  877. DUMP_ATTR(NORMAL );
  878. DUMP_ATTR(TANGENT );
  879. DUMP_ATTR(TEXCOORD_0);
  880. DUMP_ATTR(TEXCOORD_1);
  881. DUMP_ATTR(COLOR_0 );
  882. DUMP_ATTR(JOINTS_0 );
  883. DUMP_ATTR(WEIGHTS_0 );
  884. DUMP_ATTR(INDEX );
  885. }
  886. /**
  887. * @brief calculateDeviceSize
  888. * @return
  889. *
  890. * Calculate the amount of bytes this mesh takes on the
  891. * the GPU if all vertices were placed one after the
  892. * other.
  893. *
  894. * This also includes the index size!
  895. */
  896. uint64_t calculateDeviceSize() const
  897. {
  898. uint64_t size = 0;
  899. size += POSITION .getByteSize();
  900. size += NORMAL .getByteSize();
  901. size += TANGENT .getByteSize();
  902. size += TEXCOORD_0.getByteSize();
  903. size += TEXCOORD_1.getByteSize();
  904. size += COLOR_0 .getByteSize();
  905. size += JOINTS_0 .getByteSize();
  906. size += WEIGHTS_0 .getByteSize();
  907. size += INDEX.getByteSize();
  908. return size;
  909. }
  910. /**
  911. * @brief isSimilar
  912. * @param P
  913. * @return
  914. *
  915. * Returns true if two mesh primitives are similar.
  916. * Two mesh primitives are similar if they have the same attributes
  917. * and their attribute have the same type
  918. */
  919. bool isSimilar( MeshPrimitive const & P) const
  920. {
  921. return
  922. POSITION .canMerge(P.POSITION ) &&
  923. NORMAL .canMerge(P.NORMAL ) &&
  924. TANGENT .canMerge(P.TANGENT ) &&
  925. TEXCOORD_0.canMerge(P.TEXCOORD_0 ) &&
  926. TEXCOORD_1.canMerge(P.TEXCOORD_1 ) &&
  927. COLOR_0 .canMerge(P.COLOR_0 ) &&
  928. JOINTS_0 .canMerge(P.JOINTS_0 ) &&
  929. WEIGHTS_0 .canMerge(P.WEIGHTS_0 ) &&
  930. INDEX .canMerge(P.INDEX );
  931. }
  932. /**
  933. * @brief indexCount
  934. * @return
  935. *
  936. * Returns the total number of indices in the mesh
  937. */
  938. size_t indexCount() const
  939. {
  940. return INDEX.attributeCount();
  941. }
  942. /**
  943. * @brief vertexCount
  944. * @return
  945. *
  946. * Returns number of vertices in the mesh. The number of vertices
  947. * is the minimum (non-zero) attribute count of
  948. */
  949. size_t vertexCount() const
  950. {
  951. size_t count=std::numeric_limits<size_t>::max();
  952. for(auto * v : { &POSITION,
  953. &NORMAL,
  954. &TANGENT,
  955. &TEXCOORD_0,
  956. &TEXCOORD_1,
  957. &COLOR_0,
  958. &JOINTS_0,
  959. &WEIGHTS_0})
  960. {
  961. auto sh = v->attributeCount();
  962. if( sh != 0)
  963. count = std::min<size_t>(count, sh);
  964. }
  965. return count;
  966. }
  967. /**
  968. * @brief getVertexFlags
  969. * @return
  970. *
  971. * Return a the vertex flag mask where each bit
  972. * represents whether the given attribute is available.
  973. */
  974. uint32_t getVertexFlags() const
  975. {
  976. uint32_t f = 0;
  977. f |= POSITION .size() == 0 ? 0 : (1u << 0);
  978. f |= NORMAL .size() == 0 ? 0 : (1u << 1);
  979. f |= TANGENT .size() == 0 ? 0 : (1u << 2);
  980. f |= TEXCOORD_0 .size() == 0 ? 0 : (1u << 3);
  981. f |= TEXCOORD_1 .size() == 0 ? 0 : (1u << 4);
  982. f |= COLOR_0 .size() == 0 ? 0 : (1u << 5);
  983. f |= JOINTS_0 .size() == 0 ? 0 : (1u << 6);
  984. f |= WEIGHTS_0 .size() == 0 ? 0 : (1u << 7);
  985. return f;
  986. }
  987. /**
  988. * @brief getDrawCall
  989. * @return
  990. *
  991. * Returns the drawcall for the entire mesh. This can be used
  992. * if there are no primitives listed
  993. */
  994. SubMesh getDrawCall() const
  995. {
  996. SubMesh dc;
  997. dc.indexOffset = static_cast<int32_t>(0);
  998. dc.vertexOffset = static_cast<int32_t>(0);
  999. dc.vertexCount = static_cast<uint32_t>(vertexCount());
  1000. dc.indexCount = static_cast<uint32_t>(indexCount());
  1001. dc.topology = topology;
  1002. return dc;
  1003. }
  1004. /**
  1005. * @brief merge
  1006. * @param P
  1007. * @param renumberIndices
  1008. * @return
  1009. *
  1010. * Merges mesh P into the current mesh and returns the full primitive drawcall.
  1011. *
  1012. * The meshes can be merged only if they are similar (ie: they have the same attributes)
  1013. */
  1014. SubMesh merge(MeshPrimitive const & P, bool renumberIndices = false)
  1015. {
  1016. SubMesh dc;
  1017. uint32_t currentVertexCount = static_cast<uint32_t>(this->vertexCount());
  1018. uint32_t currentIndexCount = static_cast<uint32_t>(this->INDEX.size());
  1019. auto origIndexCount = indexCount();
  1020. auto origVertexCount = vertexCount();
  1021. dc.indexOffset = static_cast<int32_t>(indexCount() );
  1022. dc.vertexOffset = static_cast<int32_t>(vertexCount());
  1023. dc.vertexCount = static_cast<uint32_t>(P.vertexCount());
  1024. dc.indexCount = static_cast<uint32_t>(P.indexCount() );
  1025. if(!POSITION .canMerge(P.POSITION )) throw std::runtime_error("Cannot merge. POSITION attribute of meshes are not the same.");
  1026. if(!NORMAL .canMerge(P.NORMAL )) throw std::runtime_error("Cannot merge. NORMAL attribute of meshes are not the same.");
  1027. if(!TANGENT .canMerge(P.TANGENT )) throw std::runtime_error("Cannot merge. TANGENT attribute of meshes are not the same.");
  1028. if(!TEXCOORD_0.canMerge(P.TEXCOORD_0 )) throw std::runtime_error("Cannot merge. TEXCOORD_0 attribute of meshes are not the same.");
  1029. if(!TEXCOORD_1.canMerge(P.TEXCOORD_1 )) throw std::runtime_error("Cannot merge. TEXCOORD_1 attribute of meshes are not the same.");
  1030. if(!COLOR_0 .canMerge(P.COLOR_0 )) throw std::runtime_error("Cannot merge. COLOR_0 attribute of meshes are not the same.");
  1031. if(!JOINTS_0 .canMerge(P.JOINTS_0 )) throw std::runtime_error("Cannot merge. JOINTS_0 attribute of meshes are not the same.");
  1032. if(!WEIGHTS_0 .canMerge(P.WEIGHTS_0 )) throw std::runtime_error("Cannot merge. WEIGHTS_0 attribute of meshes are not the same.");
  1033. if(!INDEX .canMerge(P.INDEX )) throw std::runtime_error("Cannot merge. INDEX attribute of meshes are not the same.");
  1034. {
  1035. POSITION .merge(P.POSITION );
  1036. NORMAL .merge(P.NORMAL );
  1037. TANGENT .merge(P.TANGENT );
  1038. TEXCOORD_0.merge(P.TEXCOORD_0);
  1039. TEXCOORD_1.merge(P.TEXCOORD_1);
  1040. COLOR_0 .merge(P.COLOR_0 );
  1041. JOINTS_0 .merge(P.JOINTS_0 );
  1042. WEIGHTS_0 .merge(P.WEIGHTS_0 );
  1043. INDEX .merge(P.INDEX );
  1044. if(renumberIndices)
  1045. {
  1046. auto C = INDEX.size();
  1047. for(uint32_t i=currentIndexCount; i<C; i++)
  1048. {
  1049. uint32_t v = INDEX.get<uint32_t>(i) + currentVertexCount;
  1050. INDEX.set(i, v);
  1051. assert( v == INDEX.get<uint32_t>(i) );
  1052. }
  1053. dc.vertexOffset = 0;
  1054. }
  1055. for(auto & c : P.primitives)
  1056. {
  1057. auto & b = primitives.emplace_back(c);
  1058. b.indexOffset += static_cast<int32_t>(origIndexCount);
  1059. b.vertexOffset = renumberIndices ? 0 : static_cast<int>(origVertexCount);
  1060. }
  1061. return dc;
  1062. }
  1063. }
  1064. /**
  1065. * @brief calculateInterleavedStride
  1066. * @return
  1067. *
  1068. * Returns the number of bytes required to copy all the attributes
  1069. * in an interleaved layout: eg:
  1070. *
  1071. * [p0,n0,t0,p1,n1,t1...]
  1072. *
  1073. * The index buffer is not taken into account in the calculation
  1074. */
  1075. uint64_t calculateInterleavedStride() const
  1076. {
  1077. uint64_t stride=0;
  1078. for(auto * v : { &POSITION,
  1079. &NORMAL,
  1080. &TANGENT,
  1081. &TEXCOORD_0,
  1082. &TEXCOORD_1,
  1083. &COLOR_0,
  1084. &JOINTS_0,
  1085. &WEIGHTS_0})
  1086. {
  1087. if(v->attributeCount() > 0)
  1088. stride += v->getAttributeSize();
  1089. }
  1090. return stride;
  1091. }
  1092. /**
  1093. * @brief calculateBoundingSphereRadius
  1094. * @param p
  1095. * @return
  1096. *
  1097. * Calculate the bounding sphere of a specific primitive.
  1098. * The center of the sphere is positioned at the origin. If the primitive
  1099. * is fully in some quadrant, then the center of the sphere is still at the origin
  1100. */
  1101. template<typename PositionType=std::array<float,3>, typename IndexComponentType=uint32_t>
  1102. float calculateBoundingSphereRadius(SubMesh const & p) const
  1103. {
  1104. float _Max=0.0f;
  1105. forEachVertexIndex(INDEX, p, [&_Max, this](IndexComponentType i)
  1106. {
  1107. auto r = POSITION.at< PositionType >(i);
  1108. auto R2 = r[0]*r[0] + r[1]*r[1] + r[2]*r[2];
  1109. _Max = std::max( _Max, R2 );
  1110. });
  1111. return std::sqrt(_Max);
  1112. }
  1113. template<typename PositionType=std::array<float,3>, typename IndexComponentType=uint32_t>
  1114. float calculateBoundingSphereRadius() const
  1115. {
  1116. auto P = getDrawCall();
  1117. return calculateBoundingSphereRadius(P);
  1118. }
  1119. /**
  1120. * @brief copySequential
  1121. * @param data
  1122. * @return
  1123. *
  1124. * Copies all the vertex attributes sequentually into the provided buffer
  1125. * and returns the total number of vertices copied.
  1126. *
  1127. *
  1128. * [p0,n0,t0,p1,n1,t1...]
  1129. *
  1130. *
  1131. */
  1132. inline uint64_t copyVertexAttributesInterleaved(void * data, uint64_t offset=0) const
  1133. {
  1134. return copyVertexAttributesInterleaved(static_cast<uint8_t*>(data)+offset,
  1135. { &POSITION,
  1136. &NORMAL,
  1137. &TANGENT,
  1138. &TEXCOORD_0,
  1139. &TEXCOORD_1,
  1140. &COLOR_0,
  1141. &JOINTS_0,
  1142. &WEIGHTS_0});
  1143. }
  1144. /**
  1145. * @brief copyVertexAttributesInterleaved
  1146. * @param data
  1147. * @param attrs
  1148. * @return
  1149. *
  1150. * Given a list of VertexAttribute pointers, copy them interleaved into data_write_ptr
  1151. * Eg:
  1152. * copyVertexAttributeInterleaved(buffer, (&M.POSITION, &M.NORMAL, &M.TEXCOORD_0});
  1153. *
  1154. * will write the following information to buffer
  1155. *
  1156. * buffer [p0,n0,t0,p1,n1,t1,p2,n2,t2...]
  1157. *
  1158. * Returns the total number of vertices written.
  1159. *
  1160. * Requires: * All attributes must have the same number of vertices
  1161. * * data_write_ptr must have enough sequental data to write all attribute data
  1162. *
  1163. */
  1164. template<typename T>
  1165. static uint64_t copyVertexAttributesInterleaved(T * data_write_ptr, std::vector<VertexAttribute const*> const &attrs)
  1166. {
  1167. auto stride = gul::calculateInterleavedStride(attrs);
  1168. uint64_t vCount = attrs.front()->attributeCount();
  1169. uint64_t offset = 0;
  1170. for(auto * v : attrs)
  1171. {
  1172. if(v->size() == 0)
  1173. continue;
  1174. v->strideCopyOffset(
  1175. data_write_ptr,
  1176. stride,
  1177. offset,
  1178. 0,
  1179. vCount
  1180. );
  1181. offset += v->getAttributeSize();
  1182. }
  1183. return vCount;
  1184. }
  1185. template<typename T>
  1186. static uint64_t copyVertexAttributesInterleaved(std::vector<T> & dataVec, std::vector<VertexAttribute const*> const &attrs)
  1187. {
  1188. uint64_t vertexStride = 0;
  1189. uint64_t vertexCount = attrs.front()->attributeCount();
  1190. for(auto * v : attrs)
  1191. {
  1192. vertexStride += v->getAttributeSize();
  1193. }
  1194. auto totalBytes = vertexCount * vertexStride;
  1195. dataVec.resize( totalBytes / sizeof(T) );
  1196. copyVertexAttributesInterleaved(dataVec.data(), attrs);
  1197. return vertexCount*vertexStride;
  1198. }
  1199. /**
  1200. * @brief copyVertexAttributesSquential
  1201. * @param data
  1202. * @return
  1203. *
  1204. * Copies the data in sequential layout and retuns the offsets for each
  1205. * attribute.
  1206. *
  1207. * eg:
  1208. *
  1209. * p0,p1,p2,n0,n1,n2,t0,t1,t2...
  1210. *
  1211. * The index buffer is always placed at the end
  1212. */
  1213. std::vector<uint64_t> copyVertexAttributesSquential(void * data) const
  1214. {
  1215. //auto vertexCount = getVertexCount();
  1216. std::vector<uint64_t> offsets;
  1217. uint64_t offset=0;
  1218. for(auto * v : { &POSITION,
  1219. &NORMAL,
  1220. &TANGENT,
  1221. &TEXCOORD_0,
  1222. &TEXCOORD_1,
  1223. &COLOR_0,
  1224. &JOINTS_0,
  1225. &WEIGHTS_0,
  1226. &INDEX})
  1227. {
  1228. if(!v->empty())
  1229. {
  1230. offsets.push_back(offset);
  1231. //auto attrSize = v->getAttributeSize();
  1232. auto count = v->attributeCount();
  1233. assert( count * v->getAttributeSize() <= v->m_data.size());
  1234. std::memcpy( static_cast<uint8_t*>(data)+offset, v->m_data.data(), count * v->getAttributeSize());
  1235. offset += count * v->getAttributeSize();
  1236. }
  1237. else
  1238. {
  1239. offsets.push_back(0);
  1240. }
  1241. }
  1242. return offsets;
  1243. }
  1244. /**
  1245. * @brief copyIndex
  1246. * @param data
  1247. * @return
  1248. *
  1249. * Copy the index buffer
  1250. */
  1251. uint64_t copyIndex(void * data) const
  1252. {
  1253. std::memcpy(data, INDEX.m_data.data(), INDEX.m_data.size());
  1254. return INDEX.m_data.size();
  1255. }
  1256. /**
  1257. * @brief getVertexByteSize
  1258. * @return
  1259. *
  1260. * Returns the size in byte of the vertrex in bytes if all the
  1261. * attributes were interleaved
  1262. */
  1263. uint64_t getVertexByteSize() const
  1264. {
  1265. return calculateInterleavedStride();
  1266. }
  1267. inline uint64_t calculateInterleavedBufferSize() const
  1268. {
  1269. return getVertexByteSize() * vertexCount();
  1270. }
  1271. /**
  1272. * @brief fuseVertices
  1273. *
  1274. * Fuse near by vertices. This may not be accurate
  1275. */
  1276. void fuseVertices()
  1277. {
  1278. using _vec2 = std::array<float,2>;
  1279. using _vec3 = std::array<float,3>;
  1280. using _ivec3 = std::array<int32_t,3>;
  1281. std::map< std::tuple<int32_t, int32_t, int32_t>, uint32_t> posToIndex;
  1282. auto & _POS = POSITION;
  1283. auto & _NOR = NORMAL;
  1284. auto & _UV = TEXCOORD_0;
  1285. auto & _INDEX = INDEX;
  1286. std::vector<_vec3> NEW_POS;
  1287. std::vector<_vec3> NEW_NOR;
  1288. std::vector<_vec2> NEW_UV;
  1289. uint32_t index = 0;
  1290. //uint32_t j = 0;
  1291. auto vCount = vertexCount();
  1292. for(uint32_t j=0;j<vCount;j++)
  1293. {
  1294. auto p = _POS.at<_vec3>(j);
  1295. _ivec3 P{ int32_t(p[0]*100.0f) , int32_t(p[1]*100.0f) , int32_t(p[2]*100.0f) };
  1296. if( posToIndex.insert( { {P[0], P[1], P[2]}, index }).second)
  1297. {
  1298. NEW_POS.push_back(p);
  1299. if(!_NOR.empty())
  1300. NEW_NOR.push_back(_NOR.at<_vec3>(j));
  1301. if(!_UV.empty())
  1302. NEW_UV.push_back(_UV.at<_vec2>(j));
  1303. index++;
  1304. }
  1305. }
  1306. std::vector<uint32_t> newINDEX;
  1307. for(uint32_t j=0;j<_INDEX.attributeCount();j++)
  1308. {
  1309. auto i = _INDEX.at<uint32_t>(j);
  1310. auto p = _POS.at<_vec3>(i);
  1311. _ivec3 P{ int32_t(p[0]*100.0f) , int32_t(p[1]*100.0f) , int32_t(p[2]*100.0f) };
  1312. newINDEX.push_back( posToIndex.at({P[0],P[1],P[2]}) );
  1313. }
  1314. INDEX = newINDEX;
  1315. POSITION = NEW_POS;
  1316. NORMAL = NEW_NOR;
  1317. TEXCOORD_0 = NEW_UV;
  1318. }
  1319. /**
  1320. * @brief rebuildNormals
  1321. *
  1322. * Recalculate the normals for each vertex. Normals are calculated as the average
  1323. * of the face normals attached to the vertex
  1324. */
  1325. void rebuildNormals()
  1326. {
  1327. //using _vec2 = std::array<float,2>;
  1328. using _vec3 = std::array<float,3>;
  1329. {
  1330. auto & I = INDEX;
  1331. auto & P = POSITION;
  1332. std::vector< _vec3 > normals(P.attributeCount(), _vec3({0,0,0}));
  1333. auto iC = I.attributeCount();
  1334. for(size_t j=0; j< iC; j+=3)
  1335. {
  1336. auto i0 = I.at<uint32_t>(j);
  1337. auto i1 = I.at<uint32_t>(j+1);
  1338. auto i2 = I.at<uint32_t>(j+2);
  1339. assert(i0 < vertexCount());
  1340. assert(i1 < vertexCount());
  1341. assert(i2 < vertexCount());
  1342. auto p0 = P.at<_vec3>(i0);
  1343. auto p1 = P.at<_vec3>(i1);
  1344. auto p2 = P.at<_vec3>(i2);
  1345. decltype(p0) v1, v2;
  1346. v1[0] = p1[0] - p0[0];
  1347. v1[1] = p1[1] - p0[1];
  1348. v1[2] = p1[2] - p0[2];
  1349. v2[0] = p2[0] - p0[0];
  1350. v2[1] = p2[1] - p0[1];
  1351. v2[2] = p2[2] - p0[2];
  1352. auto & x = v1;
  1353. auto & y = v2;
  1354. _vec3 n = {
  1355. x[1] * y[2] - y[1] * x[2],
  1356. x[2] * y[0] - y[2] * x[0],
  1357. x[0] * y[1] - y[0] * x[1] };
  1358. normals[i0][0] += n[0];
  1359. normals[i1][0] += n[0];
  1360. normals[i2][0] += n[0];
  1361. normals[i0][1] += n[1];
  1362. normals[i1][1] += n[1];
  1363. normals[i2][1] += n[1];
  1364. normals[i0][2] += n[2];
  1365. normals[i1][2] += n[2];
  1366. normals[i2][2] += n[2];
  1367. }
  1368. for(auto & n : normals)
  1369. {
  1370. auto L = 1.0f / std::sqrt(n[0]*n[0] + n[1]*n[1] + n[2]*n[2]);
  1371. n[0] *= L;
  1372. n[1] *= L;
  1373. n[2] *= L;
  1374. }
  1375. NORMAL = normals;
  1376. }
  1377. }
  1378. };
  1379. /**
  1380. * @brief translateMesh
  1381. * @param M
  1382. * @param x
  1383. * @param y
  1384. * @param z
  1385. *
  1386. * Adds {x,y,z} to each position value
  1387. */
  1388. inline void translateMesh(MeshPrimitive & M, float x, float y, float z)
  1389. {
  1390. auto & pos = M.POSITION;
  1391. auto totalCount = pos.size();
  1392. auto numComp = pos.getNumComponents();
  1393. switch(numComp)
  1394. {
  1395. case 1:
  1396. for(uint32_t i=0;i<totalCount;i++)
  1397. {
  1398. pos.set<float>(i, pos.get<float>(i)+x);
  1399. }
  1400. break;
  1401. case 2:
  1402. for(uint32_t i=0;i<totalCount;i+=2)
  1403. {
  1404. pos.set<float>(i, pos.get<float>(i)+x);
  1405. pos.set<float>(i+1, pos.get<float>(i+1)+y);
  1406. }
  1407. break;
  1408. case 3:
  1409. for(uint32_t i=0;i<totalCount;i+=3)
  1410. {
  1411. pos.set<float>(i, pos.get<float>(i)+x);
  1412. pos.set<float>(i+1, pos.get<float>(i+1)+y);
  1413. pos.set<float>(i+2, pos.get<float>(i+2)+z);
  1414. }
  1415. break;
  1416. }
  1417. }
  1418. /**
  1419. * @brief Box
  1420. * @param dx
  1421. * @param dy
  1422. * @param dz
  1423. * @return
  1424. *
  1425. * Create a box mesh with side lengths (dx,dy,dz)
  1426. */
  1427. inline MeshPrimitive Box(float dx , float dy , float dz )
  1428. {
  1429. using _vec2 = std::array<float,2>;
  1430. using _vec3 = std::array<float,3>;
  1431. MeshPrimitive M;
  1432. auto & P = M.POSITION;
  1433. auto & N = M.NORMAL;
  1434. auto & U = M.TEXCOORD_0;
  1435. auto & I = M.INDEX;
  1436. // | Position | UV | Normal |
  1437. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{0.0f, 0.0f, 1.0f}) ;
  1438. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{0.0f, 0.0f, 1.0f}) ;
  1439. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{0.0f, 0.0f, 1.0f}) ;
  1440. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{0.0f, 0.0f, 1.0f}) ;
  1441. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{0.0f, 0.0f, 1.0f}) ;
  1442. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{0.0f, 0.0f, 1.0f}) ;
  1443. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{0.0f, 0.0f, -1.0f}) ;
  1444. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{0.0f, 0.0f, -1.0f}) ;
  1445. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{0.0f, 0.0f, -1.0f}) ;
  1446. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{0.0f, 0.0f, -1.0f}) ;
  1447. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{0.0f, 0.0f, -1.0f}) ;
  1448. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{0.0f, 0.0f, -1.0f}) ;
  1449. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{-1.0f, 0.0f, 0.0f }) ;
  1450. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{-1.0f, 0.0f, 0.0f }) ;
  1451. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{-1.0f, 0.0f, 0.0f }) ;
  1452. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{-1.0f, 0.0f, 0.0f }) ;
  1453. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{-1.0f, 0.0f, 0.0f }) ;
  1454. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{-1.0f, 0.0f, 0.0f }) ;
  1455. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{1.0f, 0.0f, 0.0f }) ;
  1456. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{1.0f, 0.0f, 0.0f }) ;
  1457. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{1.0f, 0.0f, 0.0f }) ;
  1458. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{1.0f, 0.0f, 0.0f }) ;
  1459. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{1.0f, 0.0f, 0.0f }) ;
  1460. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{1.0f, 0.0f, 0.0f }) ;
  1461. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{0.0f,-1.0f, 0.0f }) ;
  1462. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{0.0f,-1.0f, 0.0f }) ;
  1463. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{0.0f,-1.0f, 0.0f }) ;
  1464. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{0.0f,-1.0f, 0.0f }) ;
  1465. P.push_back( _vec3{dx - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{0.0f,-1.0f, 0.0f }) ;
  1466. P.push_back( _vec3{0.0f - 0.5f*dx ,0.0f - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{0.0f,-1.0f, 0.0f }) ;
  1467. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{0.0f, 1.0f, 0.0f }) ;
  1468. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{1.0f,1.0f}) ; N.push_back( _vec3{0.0f, 1.0f, 0.0f }) ;
  1469. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{0.0f, 1.0f, 0.0f }) ;
  1470. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,dz -0.5f*dz} ) ; U.push_back( _vec2{0.0f,1.0f}) ; N.push_back( _vec3{0.0f, 1.0f, 0.0f }) ;
  1471. P.push_back( _vec3{dx - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{1.0f,0.0f}) ; N.push_back( _vec3{0.0f, 1.0f, 0.0f }) ;
  1472. P.push_back( _vec3{0.0f - 0.5f*dx ,dy - 0.5f*dy ,0.0f -0.5f*dz} ) ; U.push_back( _vec2{0.0f,0.0f}) ; N.push_back( _vec3{0.0f, 1.0f, 0.0f }) ;
  1473. //=========================
  1474. // Edges of the triangle : postion delta
  1475. //=========================
  1476. I.init(eComponentType::UNSIGNED_INT, eType::SCALAR);
  1477. for( uint32_t j=0;j<36;j++)
  1478. I.push_back( j );
  1479. {
  1480. auto & dc = M.primitives.emplace_back();
  1481. dc.indexOffset = static_cast<int32_t>(0);
  1482. dc.vertexOffset = static_cast<int32_t>(0);
  1483. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1484. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1485. dc.topology = gul::Topology::TRIANGLE_LIST;
  1486. }
  1487. return M;
  1488. }
  1489. inline MeshPrimitive Box(float dx )
  1490. {
  1491. return Box(dx,dx,dx);
  1492. }
  1493. /**
  1494. * @brief Grid
  1495. * @param length - length of the grid
  1496. * @param width - width of the grid
  1497. * @param dl - grid line spacing in the length dimension
  1498. * @param dw - grid line spacing in the width dimension
  1499. * @param majorL -
  1500. * @param majorW
  1501. * @param lscale
  1502. * @param wscale
  1503. * @return
  1504. *
  1505. * Return a grid mesh. Attributes: POSITION, COLOR
  1506. */
  1507. inline MeshPrimitive Grid(int length, int width, int dl=1, int dw=1, int majorL=5, int majorW=5, float lscale=1.0f, float wscale=1.0f)
  1508. {
  1509. using _vec3 = std::array<float,3>;
  1510. using _uvec4 = std::array<uint8_t,4>;
  1511. MeshPrimitive M;
  1512. M.topology = Topology::LINE_LIST;
  1513. auto & P = M.POSITION;
  1514. auto & C = M.COLOR_0;
  1515. //_uvec4 xColor{1,1,1,255};
  1516. _uvec4 xColor{80,80,80,255};
  1517. _uvec4 majorColor{128,128,128,255};
  1518. // _uvec4 minorColor{255,0,0,255};
  1519. _uvec4 borderColor{255,255,255,255};
  1520. for(int x=-length;x<=length;x+=dl)
  1521. {
  1522. _vec3 p0{ static_cast<float>(x)*lscale, 0.0f, static_cast<float>(-width)*wscale };
  1523. _vec3 p1{ static_cast<float>(x)*lscale, 0.0f, static_cast<float>( width)*wscale };
  1524. P.push_back(p0);
  1525. P.push_back(p1);
  1526. if( x == -length || x==length)
  1527. {
  1528. C.push_back(borderColor);
  1529. C.push_back(borderColor);
  1530. }
  1531. else if( x % majorL==0)
  1532. {
  1533. C.push_back(majorColor);
  1534. C.push_back(majorColor);
  1535. }
  1536. else
  1537. {
  1538. C.push_back(xColor);
  1539. C.push_back(xColor);
  1540. }
  1541. }
  1542. for(int x=-width;x<=width;x+=dw)
  1543. {
  1544. _vec3 p0{ static_cast<float>( length)*lscale, 0.0, static_cast<float>(x)*wscale };
  1545. _vec3 p1{ static_cast<float>(-length)*lscale, 0.0, static_cast<float>(x)*wscale };
  1546. P.push_back(p0);
  1547. P.push_back(p1);
  1548. if( x == -length || x==length)
  1549. {
  1550. C.push_back(borderColor);
  1551. C.push_back(borderColor);
  1552. }
  1553. else if( x % majorW==0)
  1554. {
  1555. C.push_back(majorColor);
  1556. C.push_back(majorColor);
  1557. }
  1558. else
  1559. {
  1560. C.push_back(xColor);
  1561. C.push_back(xColor);
  1562. }
  1563. }
  1564. {
  1565. auto & dc = M.primitives.emplace_back();
  1566. dc.indexOffset = static_cast<int32_t>(0);
  1567. dc.vertexOffset = static_cast<int32_t>(0);
  1568. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1569. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1570. dc.topology = gul::Topology::TRIANGLE_LIST;
  1571. }
  1572. return M;
  1573. }
  1574. /**
  1575. * @brief Sphere
  1576. * @param radius
  1577. * @param rings
  1578. * @param sectors
  1579. * @return
  1580. *
  1581. * Return a sphere mesh
  1582. */
  1583. inline MeshPrimitive Sphere(float radius , uint32_t rings=20, uint32_t sectors=20)
  1584. {
  1585. using _vec2 = std::array<float,2>;
  1586. using _vec3 = std::array<float,3>;
  1587. MeshPrimitive M;
  1588. auto & P = M.POSITION;
  1589. auto & N = M.NORMAL;
  1590. auto & U = M.TEXCOORD_0;
  1591. auto & I = M.INDEX;
  1592. float const R = 1.0f / static_cast<float>(rings-1);
  1593. float const S = 1.0f / static_cast<float>(sectors-1);
  1594. unsigned int r, s;
  1595. for(r = 0; r < rings; r++)
  1596. {
  1597. auto rf = static_cast<float>(r);
  1598. for(s = 0; s < sectors; s++)
  1599. {
  1600. auto sf = static_cast<float>(s);
  1601. float const y = std::sin( -3.141592653589f*0.5f + 3.141592653589f * rf * R );
  1602. float const x = std::cos(2*3.141592653589f * sf * S) * std::sin( 3.141592653589f * rf * R );
  1603. float const z = std::sin(2*3.141592653589f * sf * S) * std::sin( 3.141592653589f * rf * R );
  1604. P.push_back( _vec3{ radius*x ,radius*y ,radius*z} );
  1605. U.push_back( _vec2{sf*S, rf*R} );
  1606. N.push_back( _vec3{x,y,z} );
  1607. }
  1608. }
  1609. I.init(eComponentType::UNSIGNED_INT, eType::SCALAR);
  1610. for(r = 0 ; r < rings - 1 ; r++)
  1611. {
  1612. for(s = 0 ; s < sectors - 1 ; s++)
  1613. {
  1614. I.push_back( static_cast<uint32_t>( (r+1) * sectors + s) ); //0
  1615. I.push_back( static_cast<uint32_t>( (r+1) * sectors + (s+1) ) ); //1
  1616. I.push_back( static_cast<uint32_t>( r * sectors + (s+1) )); //2
  1617. I.push_back( static_cast<uint32_t>( (r+1) * sectors + s )); //0
  1618. I.push_back( static_cast<uint32_t>( r * sectors + (s+1) )); //2
  1619. I.push_back( static_cast<uint32_t>( r * sectors + s )); //3
  1620. }
  1621. }
  1622. {
  1623. auto & dc = M.primitives.emplace_back();
  1624. dc.indexOffset = static_cast<int32_t>(0);
  1625. dc.vertexOffset = static_cast<int32_t>(0);
  1626. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1627. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1628. dc.topology = gul::Topology::TRIANGLE_LIST;
  1629. }
  1630. return M;
  1631. }
  1632. /**
  1633. * @brief Cylinder
  1634. * @param R
  1635. * @param H
  1636. * @param rSegments
  1637. * @return
  1638. *
  1639. * Return a cylinder mesh
  1640. */
  1641. inline MeshPrimitive Cylinder(float R=1.0f, float H=3.0f, uint32_t rSegments=16)
  1642. {
  1643. using _vec2 = std::array<float,2>;
  1644. using _vec3 = std::array<float,3>;
  1645. MeshPrimitive M;
  1646. std::vector<_vec3> P;// = M.POSITION; //[ vka2::PrimitiveAttribute::POSITION ];
  1647. std::vector<_vec3> N;// = M.NORMAL; //[ vka2::PrimitiveAttribute::NORMAL ];
  1648. std::vector<_vec2> U;// = M.TEXCOORD_0;//[ vka2::PrimitiveAttribute::TEXCOORD_0 ];
  1649. std::vector<uint32_t> I;// = M.INDEX;
  1650. float dt = 2.0f * 3.141592653589f / static_cast<float>(rSegments);
  1651. float t = 0;
  1652. if(1)
  1653. {
  1654. for(uint32_t r=0 ; r<rSegments; r++)
  1655. {
  1656. _vec3 p{ R*std::cos(t) , R * std::sin(t), 0 };
  1657. t += dt;
  1658. P.push_back(p);
  1659. N.push_back( _vec3{ std::cos(t), std::sin(t), 0.f } );
  1660. U.push_back( _vec2{ t, 0} );
  1661. }
  1662. for(uint32_t r=0 ; r<rSegments; r++)
  1663. {
  1664. _vec3 p{ R*std::cos(t) , R * std::sin(t), H };
  1665. t += dt;
  1666. P.push_back(p);
  1667. N.push_back( _vec3{ std::cos(t), std::sin(t), 0.f } );
  1668. U.push_back( _vec2{ t, 1} );
  1669. }
  1670. for(uint32_t i=0 ; i < rSegments; ++i)
  1671. {
  1672. const uint32_t a = (i + 0) % rSegments;
  1673. const uint32_t b = (i + 1) % rSegments;
  1674. const uint32_t c = b + rSegments;
  1675. const uint32_t d = a + rSegments;
  1676. I.push_back( static_cast<uint32_t>(a) );
  1677. I.push_back( static_cast<uint32_t>(b) );
  1678. I.push_back( static_cast<uint32_t>(c) );
  1679. I.push_back( static_cast<uint32_t>(a) );
  1680. I.push_back( static_cast<uint32_t>(c) );
  1681. I.push_back( static_cast<uint32_t>(d) );
  1682. }
  1683. M.INDEX = I;
  1684. M.POSITION = P;
  1685. M.NORMAL = N;
  1686. M.TEXCOORD_0 = U;
  1687. }
  1688. if(1)
  1689. { // top cap
  1690. MeshPrimitive M2;
  1691. std::vector<_vec3> P2;// = M2.POSITION; //[ vka2::PrimitiveAttribute::POSITION ];
  1692. std::vector<_vec3> N2;// = M2.NORMAL; //[ vka2::PrimitiveAttribute::NORMAL ];
  1693. std::vector<_vec2> U2;// = M2.TEXCOORD_0;//[ vka2::PrimitiveAttribute::TEXCOORD_0 ];
  1694. std::vector<std::array<uint32_t,3> > I2;// = M2.INDEX;
  1695. t = 0;
  1696. P2.push_back( _vec3{ 0.f, 0.f, H});
  1697. N2.push_back( _vec3{ 0.f, 0.f, 1.f } );
  1698. U2.push_back( _vec2{ 0.5f, 0.5f } );
  1699. for(uint32_t r=0 ; r < rSegments; r++)
  1700. {
  1701. _vec3 p{ R * std::cos(t) , R * std::sin(t), H };
  1702. t += dt;
  1703. P2.push_back(p);
  1704. N2.push_back( _vec3{ 0.f, 0.f, 1.f } );
  1705. U2.push_back( _vec2{ 0.5f+std::cos(t), 0.5f+std::sin(t)} );
  1706. const uint32_t A = 0;
  1707. const uint32_t B = static_cast<uint32_t>(r+1);
  1708. const uint32_t C = static_cast<uint32_t>( (r+1)%rSegments+1 );
  1709. I2.push_back( std::array<uint32_t,3>({A,B,C}));
  1710. }
  1711. M2.POSITION = P2;
  1712. M2.NORMAL = N2;
  1713. M2.TEXCOORD_0 = U2;
  1714. M2.INDEX = I2;
  1715. M2.INDEX.setType(eType::SCALAR);
  1716. M.merge(M2, true);
  1717. // bottom cap.
  1718. if(1)
  1719. {
  1720. for(auto & p : P2)
  1721. p[2] = 0.0f;
  1722. for(auto & p : N2) // flip normals
  1723. {
  1724. p[0] *= -1.f;
  1725. p[1] *= -1.f;
  1726. p[2] *= -1.f;
  1727. }
  1728. for(auto & p : I2) // reverse winding order
  1729. {
  1730. std::swap(p[0], p[2]);
  1731. }
  1732. M2.INDEX = I2;
  1733. M2.POSITION = P2;
  1734. M2.NORMAL = N2;
  1735. M2.TEXCOORD_0 = U2;
  1736. M2.INDEX.setType(eType::SCALAR);
  1737. M.merge(M2, true);
  1738. }
  1739. }
  1740. {
  1741. auto & dc = M.primitives.emplace_back();
  1742. dc.indexOffset = static_cast<int32_t>(0);
  1743. dc.vertexOffset = static_cast<int32_t>(0);
  1744. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1745. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1746. dc.topology = gul::Topology::TRIANGLE_LIST;
  1747. }
  1748. return M;
  1749. }
  1750. /**
  1751. * @brief Imposter
  1752. * @return
  1753. *
  1754. * An imposter is a simple quad in the XY plane with normal in the +Z direction
  1755. */
  1756. inline MeshPrimitive Imposter(float sideLength=1.0f)
  1757. {
  1758. MeshPrimitive M;
  1759. using _vec2 = std::array<float,2>;
  1760. using _vec3 = std::array<float,3>;
  1761. auto & P = M.POSITION;
  1762. auto & N = M.NORMAL;
  1763. auto & I = M.INDEX;
  1764. auto & U = M.TEXCOORD_0;
  1765. P.push_back( _vec3{-sideLength,-sideLength,0});
  1766. P.push_back( _vec3{ sideLength,-sideLength,0});
  1767. P.push_back( _vec3{ sideLength, sideLength,0});
  1768. P.push_back( _vec3{-sideLength, sideLength,0});
  1769. U.push_back( _vec2{0.0f, 1.0f});
  1770. U.push_back( _vec2{1.0f, 1.0f});
  1771. U.push_back( _vec2{1.0f, 0.0f});
  1772. U.push_back( _vec2{0.0f, 0.0f});
  1773. N.push_back(_vec3{0,0,1});
  1774. N.push_back(_vec3{0,0,1});
  1775. N.push_back(_vec3{0,0,1});
  1776. N.push_back(_vec3{0,0,1});
  1777. I = std::vector<uint32_t>{0,1,2,0,2,3};
  1778. {
  1779. auto & dc = M.primitives.emplace_back();
  1780. dc.indexOffset = static_cast<int32_t>(0);
  1781. dc.vertexOffset = static_cast<int32_t>(0);
  1782. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1783. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1784. dc.topology = gul::Topology::TRIANGLE_LIST;
  1785. }
  1786. return M;
  1787. }
  1788. /**
  1789. * @brief revolve
  1790. * @param XYpoints - pointer to numPoints*2 float values
  1791. * @param numPoints - total number of points
  1792. * @return
  1793. *
  1794. * Given a set of points in the XY plane, revolve the curve around
  1795. * the Z-axis
  1796. */
  1797. inline MeshPrimitive revolve(float const * XYpoints, size_t numPoints, size_t segments=10)
  1798. {
  1799. using _vec2 = std::array<float,2>;
  1800. using _vec3 = std::array<float,3>;
  1801. MeshPrimitive M;
  1802. std::vector< _vec3 > position;
  1803. std::vector< _vec3 > normal;
  1804. std::vector< _vec2 > uv;
  1805. std::vector<uint32_t> indices;
  1806. for(size_t k=0;k<segments+1;k++)
  1807. {
  1808. float t = ( float(k) / float(segments-1) );
  1809. float th = ( float(k) / float(segments) ) * 2.0f * 3.141592653589f;
  1810. for(size_t i=0;i<numPoints;i++)
  1811. {
  1812. if(k < segments)
  1813. {
  1814. float s = ( float(i) / float(numPoints-1) );
  1815. float R = XYpoints[2*i+1];
  1816. float xp = XYpoints[2*i];
  1817. float yp = R * std::cos(th);
  1818. float zp = R * std::sin(th);
  1819. position.push_back( _vec3{{ xp,yp,zp}} );
  1820. uv.push_back({s,t});
  1821. }
  1822. }
  1823. }
  1824. assert( position.size() == numPoints*segments);
  1825. auto totalPoints = position.size();
  1826. for(uint32_t k=0;k<segments;k++)
  1827. {
  1828. for(uint32_t i=0;i<numPoints-1;i++)
  1829. {
  1830. auto a = k * numPoints + i;
  1831. auto b = k * numPoints + i+1;
  1832. auto c = ( (k+1) * numPoints + i ) % totalPoints;
  1833. auto d = ( (k+1) * numPoints + i+1) % totalPoints;
  1834. indices.push_back(uint32_t(b));
  1835. indices.push_back(uint32_t(a));
  1836. indices.push_back(uint32_t(c));
  1837. indices.push_back(uint32_t(c));
  1838. indices.push_back(uint32_t(d));
  1839. indices.push_back(uint32_t(b));
  1840. }
  1841. }
  1842. M.POSITION = position;
  1843. M.INDEX = indices;
  1844. M.TEXCOORD_0 = uv;
  1845. M.rebuildNormals();
  1846. {
  1847. auto & dc = M.primitives.emplace_back();
  1848. dc.indexOffset = static_cast<int32_t>(0);
  1849. dc.vertexOffset = static_cast<int32_t>(0);
  1850. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1851. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1852. dc.topology = gul::Topology::TRIANGLE_LIST;
  1853. }
  1854. return M;
  1855. }
  1856. inline MeshPrimitive Arrow(float bodyLength, float bodyRadius, float headLength, float headRadius)
  1857. {
  1858. auto bl = bodyLength;
  1859. auto br = bodyRadius;
  1860. auto hl = headLength;
  1861. auto hr = headRadius;
  1862. std::vector<float> points;
  1863. points.push_back( 0 );
  1864. points.push_back( 0 );
  1865. points.push_back( 0 );
  1866. points.push_back( br );
  1867. points.push_back( 0 );
  1868. points.push_back( br );
  1869. points.push_back( bl );
  1870. points.push_back( br );
  1871. points.push_back( bl );
  1872. points.push_back( br );
  1873. points.push_back( bl );
  1874. points.push_back( hr );
  1875. points.push_back( bl );
  1876. points.push_back( hr );
  1877. points.push_back( hl+bl );
  1878. points.push_back( 0 );
  1879. return revolve(points.data(), points.size()/2, 10 );
  1880. }
  1881. inline MeshPrimitive ReadOBJ(std::ifstream & in)
  1882. {
  1883. using _vec2 = std::array<float,2>;
  1884. using _vec3 = std::array<float,3>;
  1885. std::vector< _vec3 > position;
  1886. std::vector< _vec3 > normal;
  1887. std::vector< _vec2 > uv;
  1888. struct faceIndex
  1889. {
  1890. uint32_t p=0;
  1891. uint32_t t=0;
  1892. uint32_t n=0;
  1893. };
  1894. std::vector< faceIndex > quads;
  1895. std::vector< faceIndex > tris;
  1896. auto split = [](std::string s, std::string delimiter)
  1897. {
  1898. using namespace std;
  1899. size_t pos_start = 0, pos_end, delim_len = delimiter.length();
  1900. string token;
  1901. vector<string> res;
  1902. while ((pos_end = s.find (delimiter, pos_start)) != string::npos) {
  1903. token = s.substr (pos_start, pos_end - pos_start);
  1904. pos_start = pos_end + delim_len;
  1905. res.push_back (token);
  1906. }
  1907. res.push_back (s.substr (pos_start));
  1908. return res;
  1909. };
  1910. auto getFace = [&](std::string s) -> faceIndex
  1911. {
  1912. faceIndex F;
  1913. auto S = split(s, "/");
  1914. if(S.size() == 3)
  1915. {
  1916. F.p = static_cast<uint32_t>(std::stoi( S[0] ));
  1917. if( S[1].size() != 0)
  1918. F.t = static_cast<uint32_t>(std::stoi(S[1]));
  1919. if( S[2].size() != 0)
  1920. F.n = static_cast<uint32_t>(std::stoi(S[2]));
  1921. return F;
  1922. }
  1923. else if(S.size() == 1)
  1924. {
  1925. F.p = static_cast<uint32_t>(std::stoi( S[0] ));
  1926. }
  1927. return F;
  1928. };
  1929. while(!in.eof())
  1930. {
  1931. std::string line;
  1932. std::string fullLine;
  1933. std::getline(in, fullLine);
  1934. std::istringstream ins(fullLine);
  1935. ins >> line;
  1936. if(line == "v")
  1937. {
  1938. _vec3 p;
  1939. ins >> p[0];
  1940. ins >> p[1];
  1941. ins >> p[2];
  1942. position.push_back(p);
  1943. }
  1944. else if(line == "vn")
  1945. {
  1946. _vec3 p;
  1947. ins >> p[0];
  1948. ins >> p[1];
  1949. ins >> p[2];
  1950. normal.push_back(p);
  1951. }
  1952. else if(line == "vt")
  1953. {
  1954. _vec2 p;
  1955. ins >> p[0];
  1956. ins >> p[1];
  1957. uv.push_back(p);
  1958. }
  1959. else if(line == "f")
  1960. {
  1961. std::string faceLine;
  1962. if(fullLine.front() == 'f')
  1963. {
  1964. faceLine = fullLine.substr(2);
  1965. }
  1966. auto sp = split(faceLine, " ");
  1967. if(sp.size() == 4)
  1968. {
  1969. for(auto & v : sp)
  1970. {
  1971. faceIndex Fa = getFace(v);
  1972. quads.push_back(Fa);
  1973. }
  1974. }
  1975. if(sp.size() == 3)
  1976. {
  1977. for(auto & v : sp)
  1978. {
  1979. faceIndex Fa = getFace(v);
  1980. tris.push_back(Fa);
  1981. }
  1982. }
  1983. //std::cout << faceLine << std::endl;
  1984. }
  1985. else
  1986. {
  1987. //std::string bah;
  1988. //std::getline(in, bah);
  1989. // std::cout << line << std::endl;
  1990. }
  1991. }
  1992. gul::MeshPrimitive M;
  1993. std::vector<_vec3> POSITION;
  1994. std::vector<_vec2> TEXCOORD;
  1995. std::vector<_vec3> NORMAL;
  1996. std::vector<uint32_t> INDEX;
  1997. for(size_t i=0;i<tris.size(); i+= 3)
  1998. {
  1999. auto & I1 = tris[i];
  2000. auto & I2 = tris[i+1];
  2001. auto & I3 = tris[i+2];
  2002. POSITION.push_back(position[I1.p-1]);
  2003. POSITION.push_back(position[I2.p-1]);
  2004. POSITION.push_back(position[I3.p-1]);
  2005. if(I1.n*I2.n*I3.n > 0 )
  2006. {
  2007. NORMAL.push_back(normal[I1.n-1]);
  2008. NORMAL.push_back(normal[I2.n-1]);
  2009. NORMAL.push_back(normal[I3.n-1]);
  2010. }
  2011. if(I1.t*I2.t*I3.t > 0 )
  2012. {
  2013. TEXCOORD.push_back(uv[I1.t-1]);
  2014. TEXCOORD.push_back(uv[I2.t-1]);
  2015. TEXCOORD.push_back(uv[I3.t-1]);
  2016. }
  2017. }
  2018. for(size_t i=0;i<quads.size(); i+= 4)
  2019. {
  2020. auto & I1 = quads[i];
  2021. auto & I2 = quads[i+1];
  2022. auto & I3 = quads[i+2];
  2023. auto & I4 = quads[i+3];
  2024. POSITION.push_back(position[I1.p - 1]);
  2025. POSITION.push_back(position[I2.p - 1]);
  2026. POSITION.push_back(position[I3.p - 1]);
  2027. POSITION.push_back(position[I1.p - 1]);
  2028. POSITION.push_back(position[I3.p - 1]);
  2029. POSITION.push_back(position[I4.p - 1]);
  2030. NORMAL.push_back(normal[I1.n - 1] );
  2031. NORMAL.push_back(normal[I2.n - 1] );
  2032. NORMAL.push_back(normal[I3.n - 1] );
  2033. NORMAL.push_back(normal[I1.n - 1] );
  2034. NORMAL.push_back(normal[I3.n - 1] );
  2035. NORMAL.push_back(normal[I4.n - 1] );
  2036. TEXCOORD.push_back(uv[I1.t - 1] );
  2037. TEXCOORD.push_back(uv[I2.t - 1] );
  2038. TEXCOORD.push_back(uv[I3.t - 1] );
  2039. TEXCOORD.push_back(uv[I1.t - 1] );
  2040. TEXCOORD.push_back(uv[I3.t - 1] );
  2041. TEXCOORD.push_back(uv[I4.t - 1] );
  2042. }
  2043. uint32_t i=0;
  2044. for(auto & x : POSITION)
  2045. {
  2046. (void)x;
  2047. INDEX.push_back(i++);
  2048. }
  2049. M.POSITION = std::move(POSITION);
  2050. M.INDEX = std::move(INDEX);
  2051. if(NORMAL.size() == 0)
  2052. {
  2053. M.rebuildNormals();
  2054. }
  2055. else
  2056. {
  2057. M.NORMAL = std::move(NORMAL);
  2058. }
  2059. M.TEXCOORD_0 = std::move(TEXCOORD);
  2060. return M;
  2061. }
  2062. }
  2063. #endif