MeshPrimitive2.h 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660
  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 componentValue
  486. * @param i
  487. * @return
  488. *
  489. * Returns the i'th component
  490. *
  491. * Assumes the underlying data is a packed array
  492. * of type, T.
  493. */
  494. template<typename T>
  495. T getComponentValue(size_t i)
  496. {
  497. T val;
  498. std::memcpy(&val, m_data.data() + i * sizeof(T), sizeof(T));
  499. return val;
  500. }
  501. template<typename T>
  502. void setComponentValue(size_t i, T const & v)
  503. {
  504. std::memcpy( m_data.data() + i * sizeof(T), &v, sizeof(T));
  505. }
  506. /**
  507. * @brief attributeCount
  508. * @return
  509. *
  510. * Returns the total number of attributes in the buffer.
  511. */
  512. uint64_t attributeCount() const
  513. {
  514. auto s = getAttributeSize();
  515. return s == 0 ? 0 : m_data.size() / s;
  516. }
  517. /**
  518. * @brief resize
  519. * @param attrCount
  520. *
  521. * Resize the attribute vector to be able to hold attrCount attributes
  522. */
  523. void resize(size_t attrCount)
  524. {
  525. m_data.resize( attrCount * getAttributeSize() );
  526. }
  527. /**
  528. * @brief canMerge
  529. * @param B
  530. * @return
  531. *
  532. * Returns wither you can merge this vertex attribute with another.
  533. * You can only merge the two if the componentType and the Type are the same
  534. */
  535. bool canMerge(VertexAttribute const & B) const
  536. {
  537. return m_componentType == B.m_componentType && m_type == B.m_type;
  538. }
  539. /**
  540. * @brief merge
  541. * @param B
  542. * @return
  543. *
  544. * Merge B to the end of the attribute vector and return the byte offset
  545. * at which the data was merged.
  546. */
  547. uint64_t merge(VertexAttribute const& B)
  548. {
  549. auto s = m_data.size();
  550. m_data.insert(m_data.end(), B.m_data.begin(), B.m_data.end());
  551. return s;
  552. }
  553. /**
  554. * @brief strideCopy
  555. * @param data
  556. * @param stride
  557. *
  558. * Copy the vertex attribute data into the memory location.
  559. *
  560. * if V = [p0,p1,p2,p3]
  561. *
  562. * Then a stride copy of strideCopy(data, 2*sizeof(p0)) will copy data as follows
  563. *
  564. * data = [p0| |p1| |p2| |p3]
  565. *
  566. * This is used to interleave multiple attribute. eg:
  567. *
  568. * positionAttribute.strideCopy(data, sizeof(vec3) )
  569. * uvAttribute.strideCopy( data+sizeof(vec3), sizeof(vec2) )
  570. */
  571. void strideCopy(void * data, uint64_t stride) const
  572. {
  573. auto c = attributeCount();
  574. auto s = getAttributeSize();
  575. auto d_in = m_data.data();
  576. auto d_out = static_cast<uint8_t*>(data);
  577. for(uint64_t i=0;i<c;i++)
  578. {
  579. std::memcpy(d_out, d_in, s);
  580. d_out += stride;
  581. d_in += s;
  582. }
  583. }
  584. /**
  585. * @brief strideCopyOffset
  586. * @param dstData - the start of the destination to copy to
  587. * @param dstByteStride - how many bytes to skip after copying each attribute
  588. * @param dstByteOffset - the offset from the start of dstData to start copying to
  589. *
  590. * @param srcStartAttributeIndex - which index in the source attribute to start copying from
  591. * @param attributeCountToCopy - number of attributes to copy
  592. * @return
  593. *
  594. * Copies the attribute data to dstData+dstByteOffset
  595. */
  596. uint64_t strideCopyOffset(void * dstData,
  597. uint64_t dstByteStride,
  598. uint64_t dstByteOffset,
  599. uint64_t srcStartAttributeIndex,
  600. uint64_t attributeCountToCopy = std::numeric_limits<uint64_t>::max()) const
  601. {
  602. auto c = std::min(attributeCount(), attributeCountToCopy);
  603. auto srcAttrSize = getAttributeSize();
  604. auto d_in = m_data.data() + srcStartAttributeIndex * srcAttrSize;
  605. auto d_in_end = std::min(d_in + srcAttrSize * attributeCountToCopy, &m_data.back()+1);
  606. auto d_out = static_cast<uint8_t*>(dstData) + dstByteOffset;
  607. while(d_in < d_in_end)
  608. {
  609. std::memcpy(d_out, d_in, srcAttrSize);
  610. d_out += dstByteStride;
  611. d_in += srcAttrSize;
  612. }
  613. return c;
  614. }
  615. /**
  616. * @brief strideCopy
  617. * @param data
  618. * @param n
  619. * @param offset
  620. * @param stride
  621. * @param num
  622. *
  623. * Copies num attributes into memory starting at data+offset with a specific stride.
  624. *
  625. * For example
  626. *
  627. * <-offset-> <--stride-->
  628. * [ | A1 | | A2 | | A3 | ]
  629. * ^--data
  630. */
  631. [[deprecated]] uint64_t strideCopy(void * data, uint64_t stride, uint64_t offset, uint64_t num = std::numeric_limits<uint64_t>::max()) const
  632. {
  633. auto c = std::min(attributeCount(), num);
  634. auto s = getAttributeSize();
  635. auto d_in = m_data.data();
  636. auto d_out = static_cast<uint8_t*>(data)+offset;
  637. for(uint64_t i=0;i<c;i++)
  638. {
  639. std::memcpy(d_out, d_in, s);
  640. d_out += stride;
  641. d_in += s;
  642. }
  643. return c;
  644. }
  645. void clear()
  646. {
  647. m_data.clear();
  648. }
  649. void setType(eType t)
  650. {
  651. m_type = t;
  652. }
  653. void setComponent(eComponentType c)
  654. {
  655. m_componentType = c;
  656. }
  657. /**
  658. * @brief getMinMax
  659. * @return
  660. *
  661. * Returns the min and max values for each component.
  662. */
  663. template<typename T>
  664. std::pair< std::vector<T>, std::vector<T>> getMinMax() const
  665. {
  666. auto & V = *this;
  667. static_assert( std::is_arithmetic_v<T>, "T must be an arithmetic type");
  668. using value_type = T;
  669. std::vector<value_type> _min(component_count(V.getType()), std::numeric_limits<value_type>::max() );
  670. std::vector<value_type> _max(component_count(V.getType()), std::numeric_limits<value_type>::lowest() );
  671. auto attrCount = attributeCount();
  672. for(uint32_t j=0;j<attrCount;j++)
  673. {
  674. for(size_t i=0;i<_min.size();i++)
  675. {
  676. _min[i] = std::min( V.at<value_type>(j, i), _min[i] );
  677. _max[i] = std::max( V.at<value_type>(j, i), _max[i] );
  678. }
  679. }
  680. return {_min, _max};
  681. }
  682. protected:
  683. friend struct MeshPrimitive;
  684. std::vector<uint8_t> m_data;
  685. eComponentType m_componentType = eComponentType::UNKNOWN;
  686. eType m_type = eType::UNKNOWN;
  687. };
  688. /**
  689. * @brief initializeFromGLTFAccessor
  690. * @param accessorCount
  691. * @param accessorComponentType
  692. * @param accessorType
  693. * @return
  694. *
  695. * Given the information from the GLTF::accessor[x] object, return
  696. * an zero initialized vertex attribute
  697. */
  698. inline VertexAttribute initializeFromGLTFAccessor(uint32_t accessorCount,
  699. uint32_t accessorComponentType,
  700. std::string accessorType)
  701. {
  702. VertexAttribute V;
  703. uint32_t accessorSize = component_size(static_cast<eComponentType>(accessorComponentType));
  704. assert(accessorSize != 0);
  705. V.setComponent(static_cast<eComponentType>(accessorComponentType));
  706. if(accessorType == "SCALAR") { V.setType(eType::SCALAR); accessorSize *= 1; }
  707. else if(accessorType == "VEC2") { V.setType(eType::VEC2); accessorSize *= 2; }
  708. else if(accessorType == "VEC3") { V.setType(eType::VEC3); accessorSize *= 3; }
  709. else if(accessorType == "VEC4") { V.setType(eType::VEC4); accessorSize *= 4; }
  710. else if(accessorType == "MAT2") { V.setType(eType::MAT2); accessorSize *= 4; }
  711. else if(accessorType == "MAT3") { V.setType(eType::MAT3); accessorSize *= 9; }
  712. else if(accessorType == "MAT4") { V.setType(eType::MAT4); accessorSize *= 16; }
  713. V.resize(accessorCount);
  714. return V;
  715. }
  716. /**
  717. * @brief fromGLTFAccessor
  718. * @param startOfBufferView
  719. * @param bufferViewByteStride
  720. * @param accessorCount
  721. * @param accessorByteOffset
  722. * @param accessorComponentType
  723. * @param accessorType
  724. * @return
  725. *
  726. * When reading a GLTF asset, a single mesh vertex attribute is defined
  727. * in an accessor/bufferView.
  728. *
  729. * Given the accessor/bufferView information in the JSON file, this
  730. * function will read the bytes from the raw bufferView data and return
  731. * a single VertexAttribute
  732. */
  733. inline VertexAttribute fromGLTFAccessor(void const *startOfBufferView,
  734. uint32_t bufferViewByteStride,
  735. uint32_t accessorCount,
  736. uint32_t accessorByteOffset,
  737. uint32_t accessorComponentType,
  738. std::string accessorType)
  739. {
  740. VertexAttribute V;
  741. uint32_t accessorSize = component_size(static_cast<eComponentType>(accessorComponentType));
  742. assert(accessorSize != 0);
  743. V.setComponent(static_cast<eComponentType>(accessorComponentType));
  744. if(accessorType == "SCALAR") { V.setType(eType::SCALAR); accessorSize *= 1; }
  745. else if(accessorType == "VEC2") { V.setType(eType::VEC2); accessorSize *= 2; }
  746. else if(accessorType == "VEC3") { V.setType(eType::VEC3); accessorSize *= 3; }
  747. else if(accessorType == "VEC4") { V.setType(eType::VEC4); accessorSize *= 4; }
  748. else if(accessorType == "MAT2") { V.setType(eType::MAT2); accessorSize *= 4; }
  749. else if(accessorType == "MAT3") { V.setType(eType::MAT3); accessorSize *= 9; }
  750. else if(accessorType == "MAT4") { V.setType(eType::MAT4); accessorSize *= 16;}
  751. V.reserveBytes( accessorCount * accessorSize );
  752. if(bufferViewByteStride == 0)
  753. {
  754. bufferViewByteStride = accessorSize;
  755. }
  756. auto _read = static_cast<uint8_t const*>(startOfBufferView) + accessorByteOffset;
  757. for(uint32_t i=0;i<accessorCount;i++)
  758. {
  759. V.appendData(_read, accessorSize);
  760. std::advance(_read, bufferViewByteStride);
  761. }
  762. return V;
  763. }
  764. //===========================================================================================================
  765. /**
  766. * @brief calculateInterleavedStride
  767. * @param attrs
  768. * @return
  769. *
  770. * Calculates the sum of each attr[i].attributeSize() skipping any attributes that dont have
  771. * items
  772. */
  773. inline uint64_t calculateInterleavedStride(std::vector<VertexAttribute const*> const &attrs)
  774. {
  775. uint64_t stride=0;
  776. for(auto * v : attrs)
  777. {
  778. if(v->size() > 0)
  779. stride += v->getAttributeSize();
  780. }
  781. return stride;
  782. }
  783. /**
  784. * @brief calculateInterleavedBytes
  785. * @param attrs
  786. * @return
  787. *
  788. * Returns the total number of bytes required to store all attributes in
  789. * interleaved format, attributes with zero attributeCount() are not included
  790. */
  791. inline uint64_t calculateInterleavedBytes(std::vector<VertexAttribute const*> const &attrs)
  792. {
  793. auto stride = calculateInterleavedStride(attrs);
  794. uint64_t vCount = 9999999999999;
  795. for(auto * v : attrs)
  796. {
  797. if(v->size() > 0)
  798. vCount = std::min(vCount,v->attributeCount());
  799. }
  800. return stride*vCount;
  801. }
  802. //===========================================================================================================
  803. enum class Topology
  804. {
  805. POINT_LIST = 0,
  806. LINE_LIST = 1,
  807. LINE_STRIP = 2,
  808. TRIANGLE_LIST = 3,
  809. TRIANGLE_STRIP = 4,
  810. TRIANGLE_FAN = 5,
  811. LINE_LIST_WITH_ADJACENCY = 6,
  812. LINE_STRIP_WITH_ADJACENCY = 7,
  813. TRIANGLE_LIST_WITH_ADJACENCY = 8,
  814. TRIANGLE_STRIP_WITH_ADJACENCY = 9,
  815. PATCH_LIST = 10,
  816. };
  817. struct DrawCall
  818. {
  819. uint32_t indexCount = 0;
  820. uint32_t vertexCount = 0;
  821. int32_t vertexOffset = 0;
  822. int32_t indexOffset = 0;
  823. Topology topology = Topology::TRIANGLE_LIST;
  824. };
  825. using SubMesh = DrawCall;
  826. /**
  827. * @brief forEachVertexIndex
  828. * @param _INDEX
  829. * @param p
  830. * @param C
  831. *
  832. * Given an index buffer and a primitive, call the callable, C for each VertexIndex in the primitive.
  833. *
  834. */
  835. template<typename Callable_t>
  836. inline void forEachVertexIndex(VertexAttribute const & _INDEX, SubMesh const & p, Callable_t && C)
  837. {
  838. if( _INDEX.getComponentType() == eComponentType::UNSIGNED_INT)
  839. {
  840. uint32_t vertexOffset = static_cast<uint32_t>(p.vertexOffset);
  841. using IndexComponentType = uint32_t;
  842. for(uint32_t i=0;i < p.indexCount ; i++)
  843. {
  844. uint32_t vertexIndex = _INDEX.at<IndexComponentType>(i + static_cast<uint32_t>(p.indexOffset))
  845. + vertexOffset;
  846. C(vertexIndex);
  847. }
  848. }
  849. }
  850. /**
  851. * @brief The MeshPrimitive struct
  852. *
  853. * A Mesh Primitive is a class which allows
  854. * you to represent a triangular mesh
  855. *
  856. */
  857. struct MeshPrimitive
  858. {
  859. using attribute_type = VertexAttribute;
  860. // list of common attributes in the order specified by the GLTF specification
  861. // initialized using the most common types
  862. attribute_type POSITION = attribute_type(eComponentType::FLOAT, eType::VEC3);
  863. attribute_type NORMAL = attribute_type(eComponentType::FLOAT, eType::VEC3);
  864. attribute_type TANGENT = attribute_type(eComponentType::FLOAT, eType::VEC4);
  865. attribute_type TEXCOORD_0 = attribute_type(eComponentType::FLOAT, eType::VEC2);
  866. attribute_type TEXCOORD_1 = attribute_type(eComponentType::FLOAT, eType::VEC2);
  867. attribute_type COLOR_0 = attribute_type(eComponentType::UNSIGNED_BYTE, eType::VEC4);
  868. attribute_type JOINTS_0 = attribute_type(eComponentType::UNSIGNED_SHORT, eType::VEC4);
  869. attribute_type WEIGHTS_0 = attribute_type(eComponentType::FLOAT, eType::VEC4);
  870. // The index buffer
  871. attribute_type INDEX = attribute_type(eComponentType::UNSIGNED_INT, eType::SCALAR);
  872. Topology topology = Topology::TRIANGLE_LIST;
  873. // a vector of primitives
  874. // each primitive is a sub component of the mesh and
  875. // contains the draw call to draw it
  876. std::vector<SubMesh> primitives;
  877. void clear()
  878. {
  879. for(auto * attr : {&POSITION ,
  880. &NORMAL ,
  881. &TANGENT ,
  882. &TEXCOORD_0,
  883. &TEXCOORD_1,
  884. &COLOR_0 ,
  885. &JOINTS_0 ,
  886. &WEIGHTS_0 ,
  887. &INDEX})
  888. {
  889. attr->clear();
  890. }
  891. }
  892. void flipWindingOrder()
  893. {
  894. if(INDEX.getComponentType() == eComponentType::UNSIGNED_INT ||
  895. INDEX.getComponentType() == eComponentType::INT)
  896. {
  897. for(uint32_t i=0;i<INDEX.attributeCount();i+=3)
  898. {
  899. auto _a = INDEX.get<uint32_t>(i);
  900. auto _b = INDEX.get<uint32_t>(i+2);
  901. INDEX.set(i, _b);
  902. INDEX.set(i+2, _a);
  903. }
  904. }
  905. if(INDEX.getComponentType() == eComponentType::UNSIGNED_SHORT ||
  906. INDEX.getComponentType() == eComponentType::SHORT)
  907. {
  908. for(uint32_t i=0;i<INDEX.attributeCount();i+=3)
  909. {
  910. auto _a = INDEX.get<uint16_t>(i);
  911. auto _b = INDEX.get<uint16_t>(i+2);
  912. INDEX.set(i, _b);
  913. INDEX.set(i+2, _a);
  914. }
  915. }
  916. if(INDEX.getComponentType() == eComponentType::UNSIGNED_BYTE ||
  917. INDEX.getComponentType() == eComponentType::BYTE)
  918. {
  919. for(uint32_t i=0;i<INDEX.attributeCount();i+=3)
  920. {
  921. auto _a = INDEX.get<uint8_t>(i);
  922. auto _b = INDEX.get<uint8_t>(i+2);
  923. INDEX.set(i, _b);
  924. INDEX.set(i+2, _a);
  925. }
  926. }
  927. }
  928. /**
  929. * @brief dump
  930. * @param out
  931. *
  932. * [experimental]
  933. * Dump the entire mesh to a simple binary file
  934. */
  935. void dump(std::ostream & out)
  936. {
  937. auto attrs = {&POSITION ,
  938. &NORMAL ,
  939. &TANGENT ,
  940. &TEXCOORD_0,
  941. &TEXCOORD_1,
  942. &COLOR_0 ,
  943. &JOINTS_0 ,
  944. &WEIGHTS_0 ,
  945. &INDEX};
  946. struct header_t
  947. {
  948. uint64_t magic = 5496876546618;
  949. uint32_t byteSize=0;
  950. uint32_t numAttributes=0;
  951. };
  952. header_t h;
  953. h.byteSize = 0;
  954. for(auto * attr : attrs)
  955. {
  956. if(attr->size())
  957. {
  958. h.numAttributes++;
  959. }
  960. }
  961. #define DUMP_ATTR(NAME ) if(NAME.size() > 0) NAME.dump(out, #NAME)
  962. out.write(reinterpret_cast<char const *>(&h), sizeof(h));
  963. DUMP_ATTR(NORMAL );
  964. DUMP_ATTR(TANGENT );
  965. DUMP_ATTR(TEXCOORD_0);
  966. DUMP_ATTR(TEXCOORD_1);
  967. DUMP_ATTR(COLOR_0 );
  968. DUMP_ATTR(JOINTS_0 );
  969. DUMP_ATTR(WEIGHTS_0 );
  970. DUMP_ATTR(INDEX );
  971. }
  972. /**
  973. * @brief calculateDeviceSize
  974. * @return
  975. *
  976. * Calculate the amount of bytes this mesh takes on the
  977. * the GPU if all vertices were placed one after the
  978. * other.
  979. *
  980. * This also includes the index size!
  981. */
  982. uint64_t calculateDeviceSize() const
  983. {
  984. uint64_t size = 0;
  985. size += POSITION .getByteSize();
  986. size += NORMAL .getByteSize();
  987. size += TANGENT .getByteSize();
  988. size += TEXCOORD_0.getByteSize();
  989. size += TEXCOORD_1.getByteSize();
  990. size += COLOR_0 .getByteSize();
  991. size += JOINTS_0 .getByteSize();
  992. size += WEIGHTS_0 .getByteSize();
  993. size += INDEX.getByteSize();
  994. return size;
  995. }
  996. /**
  997. * @brief isSimilar
  998. * @param P
  999. * @return
  1000. *
  1001. * Returns true if two mesh primitives are similar.
  1002. * Two mesh primitives are similar if they have the same attributes
  1003. * and their attribute have the same type
  1004. */
  1005. bool isSimilar( MeshPrimitive const & P) const
  1006. {
  1007. return
  1008. POSITION .canMerge(P.POSITION ) &&
  1009. NORMAL .canMerge(P.NORMAL ) &&
  1010. TANGENT .canMerge(P.TANGENT ) &&
  1011. TEXCOORD_0.canMerge(P.TEXCOORD_0 ) &&
  1012. TEXCOORD_1.canMerge(P.TEXCOORD_1 ) &&
  1013. COLOR_0 .canMerge(P.COLOR_0 ) &&
  1014. JOINTS_0 .canMerge(P.JOINTS_0 ) &&
  1015. WEIGHTS_0 .canMerge(P.WEIGHTS_0 ) &&
  1016. INDEX .canMerge(P.INDEX );
  1017. }
  1018. /**
  1019. * @brief indexCount
  1020. * @return
  1021. *
  1022. * Returns the total number of indices in the mesh
  1023. */
  1024. size_t indexCount() const
  1025. {
  1026. return INDEX.attributeCount();
  1027. }
  1028. /**
  1029. * @brief vertexCount
  1030. * @return
  1031. *
  1032. * Returns number of vertices in the mesh. The number of vertices
  1033. * is the minimum (non-zero) attribute count of
  1034. */
  1035. size_t vertexCount() const
  1036. {
  1037. size_t count=std::numeric_limits<size_t>::max();
  1038. for(auto * v : { &POSITION,
  1039. &NORMAL,
  1040. &TANGENT,
  1041. &TEXCOORD_0,
  1042. &TEXCOORD_1,
  1043. &COLOR_0,
  1044. &JOINTS_0,
  1045. &WEIGHTS_0})
  1046. {
  1047. auto sh = v->attributeCount();
  1048. if( sh != 0)
  1049. count = std::min<size_t>(count, sh);
  1050. }
  1051. return count;
  1052. }
  1053. /**
  1054. * @brief getVertexFlags
  1055. * @return
  1056. *
  1057. * Return a the vertex flag mask where each bit
  1058. * represents whether the given attribute is available.
  1059. */
  1060. uint32_t getVertexFlags() const
  1061. {
  1062. uint32_t f = 0;
  1063. f |= POSITION .size() == 0 ? 0 : (1u << 0);
  1064. f |= NORMAL .size() == 0 ? 0 : (1u << 1);
  1065. f |= TANGENT .size() == 0 ? 0 : (1u << 2);
  1066. f |= TEXCOORD_0 .size() == 0 ? 0 : (1u << 3);
  1067. f |= TEXCOORD_1 .size() == 0 ? 0 : (1u << 4);
  1068. f |= COLOR_0 .size() == 0 ? 0 : (1u << 5);
  1069. f |= JOINTS_0 .size() == 0 ? 0 : (1u << 6);
  1070. f |= WEIGHTS_0 .size() == 0 ? 0 : (1u << 7);
  1071. return f;
  1072. }
  1073. /**
  1074. * @brief getDrawCall
  1075. * @return
  1076. *
  1077. * Returns the drawcall for the entire mesh. This can be used
  1078. * if there are no primitives listed
  1079. */
  1080. SubMesh getDrawCall() const
  1081. {
  1082. DrawCall dc;
  1083. dc.indexOffset = 0;
  1084. dc.vertexOffset = 0;
  1085. dc.vertexCount = static_cast<uint32_t>(vertexCount());
  1086. dc.indexCount = static_cast<uint32_t>(indexCount());
  1087. dc.topology = topology;
  1088. return dc;
  1089. }
  1090. /**
  1091. * @brief merge
  1092. * @param P
  1093. * @param renumberIndices
  1094. * @return
  1095. *
  1096. * Merges mesh P into the current mesh and returns the full primitive drawcall.
  1097. *
  1098. * The meshes can be merged only if they are similar (ie: they have the same attributes)
  1099. */
  1100. SubMesh merge(MeshPrimitive const & P, bool renumberIndices = false)
  1101. {
  1102. SubMesh dc;
  1103. uint32_t currentVertexCount = static_cast<uint32_t>(this->vertexCount());
  1104. uint32_t currentIndexCount = static_cast<uint32_t>(this->INDEX.size());
  1105. auto origIndexCount = indexCount();
  1106. auto origVertexCount = vertexCount();
  1107. dc.indexOffset = static_cast<int32_t>(indexCount() );
  1108. dc.vertexOffset = static_cast<int32_t>(vertexCount());
  1109. dc.vertexCount = static_cast<uint32_t>(P.vertexCount());
  1110. dc.indexCount = static_cast<uint32_t>(P.indexCount() );
  1111. if(!POSITION .canMerge(P.POSITION )) throw std::runtime_error("Cannot merge. POSITION attribute of meshes are not the same.");
  1112. if(!NORMAL .canMerge(P.NORMAL )) throw std::runtime_error("Cannot merge. NORMAL attribute of meshes are not the same.");
  1113. if(!TANGENT .canMerge(P.TANGENT )) throw std::runtime_error("Cannot merge. TANGENT attribute of meshes are not the same.");
  1114. if(!TEXCOORD_0.canMerge(P.TEXCOORD_0 )) throw std::runtime_error("Cannot merge. TEXCOORD_0 attribute of meshes are not the same.");
  1115. if(!TEXCOORD_1.canMerge(P.TEXCOORD_1 )) throw std::runtime_error("Cannot merge. TEXCOORD_1 attribute of meshes are not the same.");
  1116. if(!COLOR_0 .canMerge(P.COLOR_0 )) throw std::runtime_error("Cannot merge. COLOR_0 attribute of meshes are not the same.");
  1117. if(!JOINTS_0 .canMerge(P.JOINTS_0 )) throw std::runtime_error("Cannot merge. JOINTS_0 attribute of meshes are not the same.");
  1118. if(!WEIGHTS_0 .canMerge(P.WEIGHTS_0 )) throw std::runtime_error("Cannot merge. WEIGHTS_0 attribute of meshes are not the same.");
  1119. if(!INDEX .canMerge(P.INDEX )) throw std::runtime_error("Cannot merge. INDEX attribute of meshes are not the same.");
  1120. {
  1121. POSITION .merge(P.POSITION );
  1122. NORMAL .merge(P.NORMAL );
  1123. TANGENT .merge(P.TANGENT );
  1124. TEXCOORD_0.merge(P.TEXCOORD_0);
  1125. TEXCOORD_1.merge(P.TEXCOORD_1);
  1126. COLOR_0 .merge(P.COLOR_0 );
  1127. JOINTS_0 .merge(P.JOINTS_0 );
  1128. WEIGHTS_0 .merge(P.WEIGHTS_0 );
  1129. INDEX .merge(P.INDEX );
  1130. if(renumberIndices)
  1131. {
  1132. auto C = INDEX.size();
  1133. for(uint32_t i=currentIndexCount; i<C; i++)
  1134. {
  1135. uint32_t v = INDEX.get<uint32_t>(i) + currentVertexCount;
  1136. INDEX.set(i, v);
  1137. assert( v == INDEX.get<uint32_t>(i) );
  1138. }
  1139. dc.vertexOffset = 0;
  1140. }
  1141. for(auto & c : P.primitives)
  1142. {
  1143. auto & b = primitives.emplace_back(c);
  1144. b.indexOffset += static_cast<int32_t>(origIndexCount);
  1145. b.vertexOffset = renumberIndices ? 0 : static_cast<int>(origVertexCount);
  1146. }
  1147. return dc;
  1148. }
  1149. }
  1150. /**
  1151. * @brief calculateInterleavedStride
  1152. * @return
  1153. *
  1154. * Returns the number of bytes required to copy all the attributes
  1155. * in an interleaved layout: eg:
  1156. *
  1157. * [p0,n0,t0,p1,n1,t1...]
  1158. *
  1159. * The index buffer is not taken into account in the calculation
  1160. */
  1161. uint64_t calculateInterleavedStride() const
  1162. {
  1163. uint64_t stride=0;
  1164. for(auto * v : { &POSITION,
  1165. &NORMAL,
  1166. &TANGENT,
  1167. &TEXCOORD_0,
  1168. &TEXCOORD_1,
  1169. &COLOR_0,
  1170. &JOINTS_0,
  1171. &WEIGHTS_0})
  1172. {
  1173. if(v->attributeCount() > 0)
  1174. stride += v->getAttributeSize();
  1175. }
  1176. return stride;
  1177. }
  1178. /**
  1179. * @brief calculateBoundingSphereRadius
  1180. * @param p
  1181. * @return
  1182. *
  1183. * Calculate the bounding sphere of a specific primitive.
  1184. * The center of the sphere is positioned at the origin. If the primitive
  1185. * is fully in some quadrant, then the center of the sphere is still at the origin
  1186. */
  1187. template<typename PositionType=std::array<float,3>, typename IndexComponentType=uint32_t>
  1188. float calculateBoundingSphereRadius(SubMesh const & p) const
  1189. {
  1190. float _Max=0.0f;
  1191. forEachVertexIndex(INDEX, p, [&_Max, this](IndexComponentType i)
  1192. {
  1193. auto r = POSITION.at< PositionType >(i);
  1194. auto R2 = r[0]*r[0] + r[1]*r[1] + r[2]*r[2];
  1195. _Max = std::max( _Max, R2 );
  1196. });
  1197. return std::sqrt(_Max);
  1198. }
  1199. template<typename PositionType=std::array<float,3>, typename IndexComponentType=uint32_t>
  1200. float calculateBoundingSphereRadius() const
  1201. {
  1202. auto P = getDrawCall();
  1203. return calculateBoundingSphereRadius(P);
  1204. }
  1205. /**
  1206. * @brief copySequential
  1207. * @param data
  1208. * @return
  1209. *
  1210. * Copies all the vertex attributes sequentually into the provided buffer
  1211. * and returns the total number of vertices copied.
  1212. *
  1213. *
  1214. * [p0,n0,t0,p1,n1,t1...]
  1215. *
  1216. *
  1217. */
  1218. inline uint64_t copyVertexAttributesInterleaved(void * data, uint64_t offset=0) const
  1219. {
  1220. return copyVertexAttributesInterleaved(static_cast<uint8_t*>(data)+offset,
  1221. { &POSITION,
  1222. &NORMAL,
  1223. &TANGENT,
  1224. &TEXCOORD_0,
  1225. &TEXCOORD_1,
  1226. &COLOR_0,
  1227. &JOINTS_0,
  1228. &WEIGHTS_0});
  1229. }
  1230. /**
  1231. * @brief copyVertexAttributesInterleaved
  1232. * @param data
  1233. * @param attrs
  1234. * @return
  1235. *
  1236. * Given a list of VertexAttribute pointers, copy them interleaved into data_write_ptr
  1237. * Eg:
  1238. * copyVertexAttributeInterleaved(buffer, (&M.POSITION, &M.NORMAL, &M.TEXCOORD_0});
  1239. *
  1240. * will write the following information to buffer
  1241. *
  1242. * buffer [p0,n0,t0,p1,n1,t1,p2,n2,t2...]
  1243. *
  1244. * Returns the total number of vertices written.
  1245. *
  1246. * Requires: * All attributes must have the same number of vertices
  1247. * * data_write_ptr must have enough sequental data to write all attribute data
  1248. *
  1249. */
  1250. template<typename T>
  1251. static uint64_t copyVertexAttributesInterleaved(T * data_write_ptr, std::vector<VertexAttribute const*> const &attrs)
  1252. {
  1253. auto stride = gul::calculateInterleavedStride(attrs);
  1254. uint64_t vCount = attrs.front()->attributeCount();
  1255. uint64_t offset = 0;
  1256. for(auto * v : attrs)
  1257. {
  1258. if(v->size() == 0)
  1259. continue;
  1260. v->strideCopyOffset(
  1261. data_write_ptr,
  1262. stride,
  1263. offset,
  1264. 0,
  1265. vCount
  1266. );
  1267. offset += v->getAttributeSize();
  1268. }
  1269. return vCount;
  1270. }
  1271. template<typename T>
  1272. static uint64_t copyVertexAttributesInterleaved(std::vector<T> & dataVec, std::vector<VertexAttribute const*> const &attrs)
  1273. {
  1274. uint64_t vertexStride = 0;
  1275. uint64_t vertexCount = attrs.front()->attributeCount();
  1276. for(auto * v : attrs)
  1277. {
  1278. vertexStride += v->getAttributeSize();
  1279. }
  1280. auto totalBytes = vertexCount * vertexStride;
  1281. dataVec.resize( totalBytes / sizeof(T) );
  1282. copyVertexAttributesInterleaved(dataVec.data(), attrs);
  1283. return vertexCount*vertexStride;
  1284. }
  1285. /**
  1286. * @brief copyVertexAttributesSquential
  1287. * @param data
  1288. * @return
  1289. *
  1290. * Copies the data in sequential layout and retuns the offsets for each
  1291. * attribute.
  1292. *
  1293. * eg:
  1294. *
  1295. * p0,p1,p2,n0,n1,n2,t0,t1,t2...
  1296. *
  1297. * The index buffer is always placed at the end
  1298. */
  1299. std::vector<uint64_t> copyVertexAttributesSquential(void * data) const
  1300. {
  1301. //auto vertexCount = getVertexCount();
  1302. std::vector<uint64_t> offsets;
  1303. uint64_t offset=0;
  1304. for(auto * v : { &POSITION,
  1305. &NORMAL,
  1306. &TANGENT,
  1307. &TEXCOORD_0,
  1308. &TEXCOORD_1,
  1309. &COLOR_0,
  1310. &JOINTS_0,
  1311. &WEIGHTS_0,
  1312. &INDEX})
  1313. {
  1314. if(!v->empty())
  1315. {
  1316. offsets.push_back(offset);
  1317. //auto attrSize = v->getAttributeSize();
  1318. auto count = v->attributeCount();
  1319. assert( count * v->getAttributeSize() <= v->m_data.size());
  1320. std::memcpy( static_cast<uint8_t*>(data)+offset, v->m_data.data(), count * v->getAttributeSize());
  1321. offset += count * v->getAttributeSize();
  1322. }
  1323. else
  1324. {
  1325. offsets.push_back(0);
  1326. }
  1327. }
  1328. return offsets;
  1329. }
  1330. /**
  1331. * @brief copyIndex
  1332. * @param data
  1333. * @return
  1334. *
  1335. * Copy the index buffer
  1336. */
  1337. uint64_t copyIndex(void * data) const
  1338. {
  1339. std::memcpy(data, INDEX.m_data.data(), INDEX.m_data.size());
  1340. return INDEX.m_data.size();
  1341. }
  1342. /**
  1343. * @brief getVertexByteSize
  1344. * @return
  1345. *
  1346. * Returns the size in byte of the vertrex in bytes if all the
  1347. * attributes were interleaved
  1348. */
  1349. uint64_t getVertexByteSize() const
  1350. {
  1351. return calculateInterleavedStride();
  1352. }
  1353. inline uint64_t calculateInterleavedBufferSize() const
  1354. {
  1355. return getVertexByteSize() * vertexCount();
  1356. }
  1357. /**
  1358. * @brief fuseVertices
  1359. *
  1360. * Fuse near by vertices. This may not be accurate.
  1361. *
  1362. * Returns the number of vertices that have been fused
  1363. */
  1364. size_t fuseVertices()
  1365. {
  1366. using _vec2 = std::array<float,2>;
  1367. using _vec3 = std::array<float,3>;
  1368. using _ivec3 = std::array<int32_t,3>;
  1369. std::map< std::tuple<int32_t, int32_t, int32_t>, uint32_t> posToIndex;
  1370. auto & _POS = POSITION;
  1371. auto & _NOR = NORMAL;
  1372. auto & _UV = TEXCOORD_0;
  1373. auto & _INDEX = INDEX;
  1374. std::vector<_vec3> NEW_POS;
  1375. std::vector<_vec3> NEW_NOR;
  1376. std::vector<_vec2> NEW_UV;
  1377. uint32_t index = 0;
  1378. //uint32_t j = 0;
  1379. constexpr float SC = 100.0f;
  1380. auto vCount = vertexCount();
  1381. for(uint32_t j=0;j<vCount;j++)
  1382. {
  1383. auto p = _POS.at<_vec3>(j);
  1384. _ivec3 P{ int32_t(p[0]*SC) , int32_t(p[1]*SC) , int32_t(p[2]*SC) };
  1385. if( posToIndex.insert( { {P[0], P[1], P[2]}, index }).second)
  1386. {
  1387. NEW_POS.push_back(p);
  1388. if(!_NOR.empty())
  1389. NEW_NOR.push_back(_NOR.at<_vec3>(j));
  1390. if(!_UV.empty())
  1391. NEW_UV.push_back(_UV.at<_vec2>(j));
  1392. index++;
  1393. }
  1394. }
  1395. std::vector<uint32_t> newINDEX;
  1396. for(uint32_t j=0;j<_INDEX.attributeCount();j++)
  1397. {
  1398. auto i = _INDEX.at<uint32_t>(j);
  1399. auto p = _POS.at<_vec3>(i);
  1400. _ivec3 P{ int32_t(p[0]*SC) , int32_t(p[1]*SC) , int32_t(p[2]*SC) };
  1401. newINDEX.push_back( posToIndex.at({P[0],P[1],P[2]}) );
  1402. }
  1403. INDEX = newINDEX;
  1404. POSITION = NEW_POS;
  1405. NORMAL = NEW_NOR;
  1406. TEXCOORD_0 = NEW_UV;
  1407. return vCount-vertexCount();
  1408. }
  1409. /**
  1410. * @brief rebuildNormals
  1411. *
  1412. * Recalculate the normals for each vertex. Normals are calculated as the average
  1413. * of the face normals attached to the vertex
  1414. */
  1415. void rebuildNormals()
  1416. {
  1417. //using _vec2 = std::array<float,2>;
  1418. using _vec3 = std::array<float,3>;
  1419. {
  1420. auto & I = INDEX;
  1421. auto & P = POSITION;
  1422. std::vector< _vec3 > normals(P.attributeCount(), _vec3({0,0,0}));
  1423. auto iC = I.attributeCount();
  1424. for(size_t j=0; j< iC; j+=3)
  1425. {
  1426. auto i0 = I.at<uint32_t>(j);
  1427. auto i1 = I.at<uint32_t>(j+1);
  1428. auto i2 = I.at<uint32_t>(j+2);
  1429. assert(i0 < vertexCount());
  1430. assert(i1 < vertexCount());
  1431. assert(i2 < vertexCount());
  1432. auto p0 = P.at<_vec3>(i0);
  1433. auto p1 = P.at<_vec3>(i1);
  1434. auto p2 = P.at<_vec3>(i2);
  1435. decltype(p0) v1, v2;
  1436. v1[0] = p1[0] - p0[0];
  1437. v1[1] = p1[1] - p0[1];
  1438. v1[2] = p1[2] - p0[2];
  1439. v2[0] = p2[0] - p0[0];
  1440. v2[1] = p2[1] - p0[1];
  1441. v2[2] = p2[2] - p0[2];
  1442. auto & x = v1;
  1443. auto & y = v2;
  1444. _vec3 n = {
  1445. x[1] * y[2] - y[1] * x[2],
  1446. x[2] * y[0] - y[2] * x[0],
  1447. x[0] * y[1] - y[0] * x[1] };
  1448. normals[i0][0] += n[0];
  1449. normals[i1][0] += n[0];
  1450. normals[i2][0] += n[0];
  1451. normals[i0][1] += n[1];
  1452. normals[i1][1] += n[1];
  1453. normals[i2][1] += n[1];
  1454. normals[i0][2] += n[2];
  1455. normals[i1][2] += n[2];
  1456. normals[i2][2] += n[2];
  1457. }
  1458. for(auto & n : normals)
  1459. {
  1460. auto L = 1.0f / std::sqrt(n[0]*n[0] + n[1]*n[1] + n[2]*n[2]);
  1461. n[0] *= L;
  1462. n[1] *= L;
  1463. n[2] *= L;
  1464. }
  1465. NORMAL = normals;
  1466. }
  1467. }
  1468. };
  1469. /**
  1470. * @brief translateMesh
  1471. * @param M
  1472. * @param x
  1473. * @param y
  1474. * @param z
  1475. *
  1476. * Adds {x,y,z} to each position value
  1477. */
  1478. inline void translateMesh(MeshPrimitive & M, float x, float y, float z)
  1479. {
  1480. auto & pos = M.POSITION;
  1481. auto totalCount = pos.size();
  1482. auto numComp = pos.getNumComponents();
  1483. switch(numComp)
  1484. {
  1485. case 1:
  1486. for(uint32_t i=0;i<totalCount;i++)
  1487. {
  1488. pos.set<float>(i, pos.get<float>(i)+x);
  1489. }
  1490. break;
  1491. case 2:
  1492. for(uint32_t i=0;i<totalCount;i+=2)
  1493. {
  1494. pos.set<float>(i, pos.get<float>(i)+x);
  1495. pos.set<float>(i+1, pos.get<float>(i+1)+y);
  1496. }
  1497. break;
  1498. case 3:
  1499. for(uint32_t i=0;i<totalCount;i+=3)
  1500. {
  1501. pos.set<float>(i, pos.get<float>(i)+x);
  1502. pos.set<float>(i+1, pos.get<float>(i+1)+y);
  1503. pos.set<float>(i+2, pos.get<float>(i+2)+z);
  1504. }
  1505. break;
  1506. }
  1507. }
  1508. /**
  1509. * @brief Box
  1510. * @param dx
  1511. * @param dy
  1512. * @param dz
  1513. * @return
  1514. *
  1515. * Create a box mesh with side lengths (dx,dy,dz)
  1516. */
  1517. inline MeshPrimitive Box(float dx , float dy , float dz )
  1518. {
  1519. using _vec2 = std::array<float,2>;
  1520. using _vec3 = std::array<float,3>;
  1521. MeshPrimitive M;
  1522. auto & P = M.POSITION;
  1523. auto & N = M.NORMAL;
  1524. auto & U = M.TEXCOORD_0;
  1525. auto & I = M.INDEX;
  1526. // | Position | UV | Normal |
  1527. 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}) ;
  1528. 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}) ;
  1529. 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}) ;
  1530. 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}) ;
  1531. 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}) ;
  1532. 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}) ;
  1533. 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}) ;
  1534. 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}) ;
  1535. 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}) ;
  1536. 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}) ;
  1537. 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}) ;
  1538. 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}) ;
  1539. 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 }) ;
  1540. 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 }) ;
  1541. 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 }) ;
  1542. 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 }) ;
  1543. 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 }) ;
  1544. 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 }) ;
  1545. 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 }) ;
  1546. 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 }) ;
  1547. 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 }) ;
  1548. 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 }) ;
  1549. 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 }) ;
  1550. 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 }) ;
  1551. 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 }) ;
  1552. 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 }) ;
  1553. 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 }) ;
  1554. 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 }) ;
  1555. 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 }) ;
  1556. 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 }) ;
  1557. 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 }) ;
  1558. 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 }) ;
  1559. 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 }) ;
  1560. 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 }) ;
  1561. 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 }) ;
  1562. 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 }) ;
  1563. //=========================
  1564. // Edges of the triangle : postion delta
  1565. //=========================
  1566. I.init(eComponentType::UNSIGNED_INT, eType::SCALAR);
  1567. for( uint32_t j=0;j<36;j++)
  1568. {
  1569. auto y = P.get<_vec3>(j);
  1570. y[1] *= -1;
  1571. P.set(j, y);
  1572. I.push_back( j );
  1573. }
  1574. M.flipWindingOrder();
  1575. {
  1576. auto & dc = M.primitives.emplace_back();
  1577. dc.indexOffset = 0;
  1578. dc.vertexOffset = 0;
  1579. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1580. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1581. dc.topology = gul::Topology::TRIANGLE_LIST;
  1582. }
  1583. return M;
  1584. }
  1585. inline MeshPrimitive Box(float dx )
  1586. {
  1587. return Box(dx,dx,dx);
  1588. }
  1589. /**
  1590. * @brief Grid
  1591. * @param length - length of the grid
  1592. * @param width - width of the grid
  1593. * @param dl - grid line spacing in the length dimension
  1594. * @param dw - grid line spacing in the width dimension
  1595. * @param majorL -
  1596. * @param majorW
  1597. * @param lscale
  1598. * @param wscale
  1599. * @return
  1600. *
  1601. * Return a grid mesh. Attributes: POSITION, COLOR
  1602. */
  1603. 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)
  1604. {
  1605. using _vec3 = std::array<float,3>;
  1606. using _uvec4 = std::array<uint8_t,4>;
  1607. MeshPrimitive M;
  1608. M.topology = Topology::LINE_LIST;
  1609. auto & P = M.POSITION;
  1610. auto & C = M.COLOR_0;
  1611. //_uvec4 xColor{1,1,1,255};
  1612. _uvec4 xColor{80,80,80,255};
  1613. _uvec4 majorColor{128,128,128,255};
  1614. // _uvec4 minorColor{255,0,0,255};
  1615. _uvec4 borderColor{255,255,255,255};
  1616. for(int x=-length;x<=length;x+=dl)
  1617. {
  1618. _vec3 p0{ static_cast<float>(x)*lscale, 0.0f, static_cast<float>(-width)*wscale };
  1619. _vec3 p1{ static_cast<float>(x)*lscale, 0.0f, static_cast<float>( width)*wscale };
  1620. P.push_back(p0);
  1621. P.push_back(p1);
  1622. if( x == -length || x==length)
  1623. {
  1624. C.push_back(borderColor);
  1625. C.push_back(borderColor);
  1626. }
  1627. else if( x % majorL==0)
  1628. {
  1629. C.push_back(majorColor);
  1630. C.push_back(majorColor);
  1631. }
  1632. else
  1633. {
  1634. C.push_back(xColor);
  1635. C.push_back(xColor);
  1636. }
  1637. }
  1638. for(int x=-width;x<=width;x+=dw)
  1639. {
  1640. _vec3 p0{ static_cast<float>( length)*lscale, 0.0, static_cast<float>(x)*wscale };
  1641. _vec3 p1{ static_cast<float>(-length)*lscale, 0.0, static_cast<float>(x)*wscale };
  1642. P.push_back(p0);
  1643. P.push_back(p1);
  1644. if( x == -length || x==length)
  1645. {
  1646. C.push_back(borderColor);
  1647. C.push_back(borderColor);
  1648. }
  1649. else if( x % majorW==0)
  1650. {
  1651. C.push_back(majorColor);
  1652. C.push_back(majorColor);
  1653. }
  1654. else
  1655. {
  1656. C.push_back(xColor);
  1657. C.push_back(xColor);
  1658. }
  1659. }
  1660. {
  1661. auto & dc = M.primitives.emplace_back();
  1662. dc.indexOffset = 0;
  1663. dc.vertexOffset = 0;
  1664. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1665. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1666. dc.topology = gul::Topology::TRIANGLE_LIST;
  1667. }
  1668. return M;
  1669. }
  1670. /**
  1671. * @brief Sphere
  1672. * @param radius
  1673. * @param rings
  1674. * @param sectors
  1675. * @return
  1676. *
  1677. * Return a sphere mesh
  1678. */
  1679. inline MeshPrimitive Sphere(float radius , uint32_t rings=20, uint32_t sectors=20)
  1680. {
  1681. using _vec2 = std::array<float,2>;
  1682. using _vec3 = std::array<float,3>;
  1683. MeshPrimitive M;
  1684. auto & P = M.POSITION;
  1685. auto & N = M.NORMAL;
  1686. auto & U = M.TEXCOORD_0;
  1687. auto & I = M.INDEX;
  1688. float const R = 1.0f / static_cast<float>(rings-1);
  1689. float const S = 1.0f / static_cast<float>(sectors-1);
  1690. unsigned int r, s;
  1691. for(r = 0; r < rings; r++)
  1692. {
  1693. auto rf = static_cast<float>(r);
  1694. for(s = 0; s < sectors; s++)
  1695. {
  1696. auto sf = static_cast<float>(s);
  1697. float const y = std::sin( -3.141592653589f*0.5f + 3.141592653589f * rf * R );
  1698. float const x = std::cos(2*3.141592653589f * sf * S) * std::sin( 3.141592653589f * rf * R );
  1699. float const z = std::sin(2*3.141592653589f * sf * S) * std::sin( 3.141592653589f * rf * R );
  1700. P.push_back( _vec3{ radius*x ,radius*y ,radius*z} );
  1701. U.push_back( _vec2{sf*S, rf*R} );
  1702. N.push_back( _vec3{x,y,z} );
  1703. }
  1704. }
  1705. I.init(eComponentType::UNSIGNED_INT, eType::SCALAR);
  1706. for(r = 0 ; r < rings - 1 ; r++)
  1707. {
  1708. for(s = 0 ; s < sectors - 1 ; s++)
  1709. {
  1710. I.push_back( ( (r+1) * sectors + s) ); //0
  1711. I.push_back( ( (r+1) * sectors + (s+1) ) ); //1
  1712. I.push_back( ( r * sectors + (s+1) )); //2
  1713. I.push_back( ( (r+1) * sectors + s )); //0
  1714. I.push_back( ( r * sectors + (s+1) )); //2
  1715. I.push_back( ( r * sectors + s )); //3
  1716. }
  1717. }
  1718. {
  1719. auto & dc = M.primitives.emplace_back();
  1720. dc.indexOffset = 0;
  1721. dc.vertexOffset = 0;
  1722. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1723. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1724. dc.topology = gul::Topology::TRIANGLE_LIST;
  1725. }
  1726. return M;
  1727. }
  1728. /**
  1729. * @brief Cylinder
  1730. * @param R
  1731. * @param H
  1732. * @param rSegments
  1733. * @return
  1734. *
  1735. * Return a cylinder mesh
  1736. */
  1737. inline MeshPrimitive Cylinder(float R=1.0f, float H=3.0f, uint32_t rSegments=16)
  1738. {
  1739. using _vec2 = std::array<float,2>;
  1740. using _vec3 = std::array<float,3>;
  1741. MeshPrimitive M;
  1742. std::vector<_vec3> P;// = M.POSITION; //[ vka2::PrimitiveAttribute::POSITION ];
  1743. std::vector<_vec3> N;// = M.NORMAL; //[ vka2::PrimitiveAttribute::NORMAL ];
  1744. std::vector<_vec2> U;// = M.TEXCOORD_0;//[ vka2::PrimitiveAttribute::TEXCOORD_0 ];
  1745. std::vector<uint32_t> I;// = M.INDEX;
  1746. float dt = 2.0f * 3.141592653589f / static_cast<float>(rSegments);
  1747. float t = 0;
  1748. if(1)
  1749. {
  1750. for(uint32_t r=0 ; r<rSegments; r++)
  1751. {
  1752. _vec3 p{ R*std::cos(t) , R * std::sin(t), 0 };
  1753. t += dt;
  1754. P.push_back(p);
  1755. N.push_back( _vec3{ std::cos(t), std::sin(t), 0.f } );
  1756. U.push_back( _vec2{ t, 0} );
  1757. }
  1758. for(uint32_t r=0 ; r<rSegments; r++)
  1759. {
  1760. _vec3 p{ R*std::cos(t) , R * std::sin(t), H };
  1761. t += dt;
  1762. P.push_back(p);
  1763. N.push_back( _vec3{ std::cos(t), std::sin(t), 0.f } );
  1764. U.push_back( _vec2{ t, 1} );
  1765. }
  1766. for(uint32_t i=0 ; i < rSegments; ++i)
  1767. {
  1768. const uint32_t a = (i + 0) % rSegments;
  1769. const uint32_t b = (i + 1) % rSegments;
  1770. const uint32_t c = b + rSegments;
  1771. const uint32_t d = a + rSegments;
  1772. I.push_back( static_cast<uint32_t>(a) );
  1773. I.push_back( static_cast<uint32_t>(b) );
  1774. I.push_back( static_cast<uint32_t>(c) );
  1775. I.push_back( static_cast<uint32_t>(a) );
  1776. I.push_back( static_cast<uint32_t>(c) );
  1777. I.push_back( static_cast<uint32_t>(d) );
  1778. }
  1779. M.INDEX = I;
  1780. M.POSITION = P;
  1781. M.NORMAL = N;
  1782. M.TEXCOORD_0 = U;
  1783. }
  1784. if(1)
  1785. { // top cap
  1786. MeshPrimitive M2;
  1787. std::vector<_vec3> P2;// = M2.POSITION; //[ vka2::PrimitiveAttribute::POSITION ];
  1788. std::vector<_vec3> N2;// = M2.NORMAL; //[ vka2::PrimitiveAttribute::NORMAL ];
  1789. std::vector<_vec2> U2;// = M2.TEXCOORD_0;//[ vka2::PrimitiveAttribute::TEXCOORD_0 ];
  1790. std::vector<std::array<uint32_t,3> > I2;// = M2.INDEX;
  1791. t = 0;
  1792. P2.push_back( _vec3{ 0.f, 0.f, H});
  1793. N2.push_back( _vec3{ 0.f, 0.f, 1.f } );
  1794. U2.push_back( _vec2{ 0.5f, 0.5f } );
  1795. for(uint32_t r=0 ; r < rSegments; r++)
  1796. {
  1797. _vec3 p{ R * std::cos(t) , R * std::sin(t), H };
  1798. t += dt;
  1799. P2.push_back(p);
  1800. N2.push_back( _vec3{ 0.f, 0.f, 1.f } );
  1801. U2.push_back( _vec2{ 0.5f+std::cos(t), 0.5f+std::sin(t)} );
  1802. const uint32_t A = 0;
  1803. const uint32_t B = r+1;
  1804. const uint32_t C = (r+1)%rSegments+1 ;
  1805. I2.push_back( std::array<uint32_t,3>({A,B,C}));
  1806. }
  1807. M2.POSITION = P2;
  1808. M2.NORMAL = N2;
  1809. M2.TEXCOORD_0 = U2;
  1810. M2.INDEX = I2;
  1811. M2.INDEX.setType(eType::SCALAR);
  1812. M.merge(M2, true);
  1813. // bottom cap.
  1814. if(1)
  1815. {
  1816. for(auto & p : P2)
  1817. p[2] = 0.0f;
  1818. for(auto & p : N2) // flip normals
  1819. {
  1820. p[0] *= -1.f;
  1821. p[1] *= -1.f;
  1822. p[2] *= -1.f;
  1823. }
  1824. for(auto & p : I2) // reverse winding order
  1825. {
  1826. std::swap(p[0], p[2]);
  1827. }
  1828. M2.INDEX = I2;
  1829. M2.POSITION = P2;
  1830. M2.NORMAL = N2;
  1831. M2.TEXCOORD_0 = U2;
  1832. M2.INDEX.setType(eType::SCALAR);
  1833. M.merge(M2, true);
  1834. }
  1835. }
  1836. {
  1837. auto & dc = M.primitives.emplace_back();
  1838. dc.indexOffset = 0;
  1839. dc.vertexOffset = 0;
  1840. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1841. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1842. dc.topology = gul::Topology::TRIANGLE_LIST;
  1843. }
  1844. return M;
  1845. }
  1846. /**
  1847. * @brief Imposter
  1848. * @return
  1849. *
  1850. * An imposter is a simple quad in the XY plane with normal in the +Z direction
  1851. */
  1852. inline MeshPrimitive Imposter(float sideLength=1.0f)
  1853. {
  1854. MeshPrimitive M;
  1855. using _vec2 = std::array<float,2>;
  1856. using _vec3 = std::array<float,3>;
  1857. auto & P = M.POSITION;
  1858. auto & N = M.NORMAL;
  1859. auto & I = M.INDEX;
  1860. auto & U = M.TEXCOORD_0;
  1861. P.push_back( _vec3{-sideLength,-sideLength,0});
  1862. P.push_back( _vec3{ sideLength,-sideLength,0});
  1863. P.push_back( _vec3{ sideLength, sideLength,0});
  1864. P.push_back( _vec3{-sideLength, sideLength,0});
  1865. U.push_back( _vec2{0.0f, 1.0f});
  1866. U.push_back( _vec2{1.0f, 1.0f});
  1867. U.push_back( _vec2{1.0f, 0.0f});
  1868. U.push_back( _vec2{0.0f, 0.0f});
  1869. N.push_back(_vec3{0,0,1});
  1870. N.push_back(_vec3{0,0,1});
  1871. N.push_back(_vec3{0,0,1});
  1872. N.push_back(_vec3{0,0,1});
  1873. I = std::vector<uint32_t>{0,1,2,0,2,3};
  1874. {
  1875. auto & dc = M.primitives.emplace_back();
  1876. dc.indexOffset = 0;
  1877. dc.vertexOffset = 0;
  1878. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1879. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1880. dc.topology = gul::Topology::TRIANGLE_LIST;
  1881. }
  1882. return M;
  1883. }
  1884. /**
  1885. * @brief revolve
  1886. * @param XYpoints - pointer to numPoints*2 float values
  1887. * @param numPoints - total number of points
  1888. * @return
  1889. *
  1890. * Given a set of points in the XY plane, revolve the curve around
  1891. * the Z-axis
  1892. */
  1893. inline MeshPrimitive revolve(float const * XYpoints, size_t numPoints, size_t segments=10)
  1894. {
  1895. using _vec2 = std::array<float,2>;
  1896. using _vec3 = std::array<float,3>;
  1897. MeshPrimitive M;
  1898. std::vector< _vec3 > position;
  1899. std::vector< _vec3 > normal;
  1900. std::vector< _vec2 > uv;
  1901. std::vector<uint32_t> indices;
  1902. for(size_t k=0;k<segments+1;k++)
  1903. {
  1904. float t = ( float(k) / float(segments-1) );
  1905. float th = ( float(k) / float(segments) ) * 2.0f * 3.141592653589f;
  1906. for(size_t i=0;i<numPoints;i++)
  1907. {
  1908. if(k < segments)
  1909. {
  1910. float s = ( float(i) / float(numPoints-1) );
  1911. float R = XYpoints[2*i+1];
  1912. float xp = XYpoints[2*i];
  1913. float yp = R * std::cos(th);
  1914. float zp = R * std::sin(th);
  1915. position.push_back( _vec3{{ xp,yp,zp}} );
  1916. uv.push_back({s,t});
  1917. }
  1918. }
  1919. }
  1920. assert( position.size() == numPoints*segments);
  1921. auto totalPoints = position.size();
  1922. for(uint32_t k=0;k<segments;k++)
  1923. {
  1924. for(uint32_t i=0;i<numPoints-1;i++)
  1925. {
  1926. auto a = k * numPoints + i;
  1927. auto b = k * numPoints + i+1;
  1928. auto c = ( (k+1) * numPoints + i ) % totalPoints;
  1929. auto d = ( (k+1) * numPoints + i+1) % totalPoints;
  1930. indices.push_back(uint32_t(b));
  1931. indices.push_back(uint32_t(a));
  1932. indices.push_back(uint32_t(c));
  1933. indices.push_back(uint32_t(c));
  1934. indices.push_back(uint32_t(d));
  1935. indices.push_back(uint32_t(b));
  1936. }
  1937. }
  1938. M.POSITION = position;
  1939. M.INDEX = indices;
  1940. M.TEXCOORD_0 = uv;
  1941. M.rebuildNormals();
  1942. {
  1943. auto & dc = M.primitives.emplace_back();
  1944. dc.indexOffset = 0;
  1945. dc.vertexOffset = 0;
  1946. dc.vertexCount = static_cast<uint32_t>(M.vertexCount());
  1947. dc.indexCount = static_cast<uint32_t>(M.indexCount());
  1948. dc.topology = gul::Topology::TRIANGLE_LIST;
  1949. }
  1950. return M;
  1951. }
  1952. inline MeshPrimitive Arrow(float bodyLength, float bodyRadius, float headLength, float headRadius)
  1953. {
  1954. auto bl = bodyLength;
  1955. auto br = bodyRadius;
  1956. auto hl = headLength;
  1957. auto hr = headRadius;
  1958. std::vector<float> points;
  1959. points.push_back( 0 );
  1960. points.push_back( 0 );
  1961. points.push_back( 0 );
  1962. points.push_back( br );
  1963. points.push_back( 0 );
  1964. points.push_back( br );
  1965. points.push_back( bl );
  1966. points.push_back( br );
  1967. points.push_back( bl );
  1968. points.push_back( br );
  1969. points.push_back( bl );
  1970. points.push_back( hr );
  1971. points.push_back( bl );
  1972. points.push_back( hr );
  1973. points.push_back( hl+bl );
  1974. points.push_back( 0 );
  1975. return revolve(points.data(), points.size()/2, 10 );
  1976. }
  1977. inline MeshPrimitive ReadOBJ(std::ifstream & in)
  1978. {
  1979. using _vec2 = std::array<float,2>;
  1980. using _vec3 = std::array<float,3>;
  1981. std::vector< _vec3 > position;
  1982. std::vector< _vec3 > normal;
  1983. std::vector< _vec2 > uv;
  1984. struct faceIndex
  1985. {
  1986. uint32_t p=0;
  1987. uint32_t t=0;
  1988. uint32_t n=0;
  1989. };
  1990. std::vector< faceIndex > quads;
  1991. std::vector< faceIndex > tris;
  1992. auto split = [](std::string s, std::string delimiter)
  1993. {
  1994. using namespace std;
  1995. size_t pos_start = 0, pos_end, delim_len = delimiter.length();
  1996. string token;
  1997. vector<string> res;
  1998. while ((pos_end = s.find (delimiter, pos_start)) != string::npos) {
  1999. token = s.substr (pos_start, pos_end - pos_start);
  2000. pos_start = pos_end + delim_len;
  2001. res.push_back (token);
  2002. }
  2003. res.push_back (s.substr (pos_start));
  2004. return res;
  2005. };
  2006. auto getFace = [&](std::string s) -> faceIndex
  2007. {
  2008. faceIndex F;
  2009. auto S = split(s, "/");
  2010. if(S.size() == 3)
  2011. {
  2012. F.p = static_cast<uint32_t>(std::stoi( S[0] ));
  2013. if( S[1].size() != 0)
  2014. F.t = static_cast<uint32_t>(std::stoi(S[1]));
  2015. if( S[2].size() != 0)
  2016. F.n = static_cast<uint32_t>(std::stoi(S[2]));
  2017. return F;
  2018. }
  2019. else if(S.size() == 1)
  2020. {
  2021. F.p = static_cast<uint32_t>(std::stoi( S[0] ));
  2022. }
  2023. return F;
  2024. };
  2025. while(!in.eof())
  2026. {
  2027. std::string line;
  2028. std::string fullLine;
  2029. std::getline(in, fullLine);
  2030. std::istringstream ins(fullLine);
  2031. ins >> line;
  2032. if(line == "v")
  2033. {
  2034. _vec3 p;
  2035. ins >> p[0];
  2036. ins >> p[1];
  2037. ins >> p[2];
  2038. position.push_back(p);
  2039. }
  2040. else if(line == "vn")
  2041. {
  2042. _vec3 p;
  2043. ins >> p[0];
  2044. ins >> p[1];
  2045. ins >> p[2];
  2046. normal.push_back(p);
  2047. }
  2048. else if(line == "vt")
  2049. {
  2050. _vec2 p;
  2051. ins >> p[0];
  2052. ins >> p[1];
  2053. uv.push_back(p);
  2054. }
  2055. else if(line == "f")
  2056. {
  2057. std::string faceLine;
  2058. if(fullLine.front() == 'f')
  2059. {
  2060. faceLine = fullLine.substr(2);
  2061. }
  2062. auto sp = split(faceLine, " ");
  2063. if(sp.size() == 4)
  2064. {
  2065. for(auto & v : sp)
  2066. {
  2067. faceIndex Fa = getFace(v);
  2068. quads.push_back(Fa);
  2069. }
  2070. }
  2071. if(sp.size() == 3)
  2072. {
  2073. for(auto & v : sp)
  2074. {
  2075. faceIndex Fa = getFace(v);
  2076. tris.push_back(Fa);
  2077. }
  2078. }
  2079. //std::cout << faceLine << std::endl;
  2080. }
  2081. else
  2082. {
  2083. //std::string bah;
  2084. //std::getline(in, bah);
  2085. // std::cout << line << std::endl;
  2086. }
  2087. }
  2088. gul::MeshPrimitive M;
  2089. std::vector<_vec3> POSITION;
  2090. std::vector<_vec2> TEXCOORD;
  2091. std::vector<_vec3> NORMAL;
  2092. std::vector<uint32_t> INDEX;
  2093. for(size_t i=0;i<tris.size(); i+= 3)
  2094. {
  2095. auto & I1 = tris[i];
  2096. auto & I2 = tris[i+1];
  2097. auto & I3 = tris[i+2];
  2098. POSITION.push_back(position[I1.p-1]);
  2099. POSITION.push_back(position[I2.p-1]);
  2100. POSITION.push_back(position[I3.p-1]);
  2101. if(I1.n*I2.n*I3.n > 0 )
  2102. {
  2103. NORMAL.push_back(normal[I1.n-1]);
  2104. NORMAL.push_back(normal[I2.n-1]);
  2105. NORMAL.push_back(normal[I3.n-1]);
  2106. }
  2107. if(I1.t*I2.t*I3.t > 0 )
  2108. {
  2109. TEXCOORD.push_back(uv[I1.t-1]);
  2110. TEXCOORD.push_back(uv[I2.t-1]);
  2111. TEXCOORD.push_back(uv[I3.t-1]);
  2112. }
  2113. }
  2114. for(size_t i=0;i<quads.size(); i+= 4)
  2115. {
  2116. auto & I1 = quads[i];
  2117. auto & I2 = quads[i+1];
  2118. auto & I3 = quads[i+2];
  2119. auto & I4 = quads[i+3];
  2120. POSITION.push_back(position[I1.p - 1]);
  2121. POSITION.push_back(position[I2.p - 1]);
  2122. POSITION.push_back(position[I3.p - 1]);
  2123. POSITION.push_back(position[I1.p - 1]);
  2124. POSITION.push_back(position[I3.p - 1]);
  2125. POSITION.push_back(position[I4.p - 1]);
  2126. NORMAL.push_back(normal[I1.n - 1] );
  2127. NORMAL.push_back(normal[I2.n - 1] );
  2128. NORMAL.push_back(normal[I3.n - 1] );
  2129. NORMAL.push_back(normal[I1.n - 1] );
  2130. NORMAL.push_back(normal[I3.n - 1] );
  2131. NORMAL.push_back(normal[I4.n - 1] );
  2132. TEXCOORD.push_back(uv[I1.t - 1] );
  2133. TEXCOORD.push_back(uv[I2.t - 1] );
  2134. TEXCOORD.push_back(uv[I3.t - 1] );
  2135. TEXCOORD.push_back(uv[I1.t - 1] );
  2136. TEXCOORD.push_back(uv[I3.t - 1] );
  2137. TEXCOORD.push_back(uv[I4.t - 1] );
  2138. }
  2139. uint32_t i=0;
  2140. for(auto & x : POSITION)
  2141. {
  2142. (void)x;
  2143. INDEX.push_back(i++);
  2144. }
  2145. M.POSITION = std::move(POSITION);
  2146. M.INDEX = std::move(INDEX);
  2147. if(NORMAL.size() == 0)
  2148. {
  2149. M.rebuildNormals();
  2150. }
  2151. else
  2152. {
  2153. M.NORMAL = std::move(NORMAL);
  2154. }
  2155. M.TEXCOORD_0 = std::move(TEXCOORD);
  2156. return M;
  2157. }
  2158. inline MeshPrimitive readOBJ2(std::istream & SSO)
  2159. {
  2160. using vec3 = std::array<float, 3>;
  2161. using vec2 = std::array<float, 2>;
  2162. using tri_face = std::array<uint32_t, 3>;
  2163. using quad_face = std::array<uint32_t, 4>;
  2164. std::vector<vec3> pos, norm;
  2165. std::vector<vec2> uv;
  2166. std::vector<tri_face> tris;
  2167. std::vector<quad_face> quads;
  2168. using vertex_id = std::tuple<uint32_t, uint32_t, uint32_t>;
  2169. std::map<vertex_id, uint32_t> vertex_to_index;
  2170. std::string blah;
  2171. std::string line;
  2172. while(!SSO.eof())
  2173. {
  2174. std::getline(SSO, line);
  2175. if(line.empty())
  2176. continue;
  2177. if(line[1] == 'n')
  2178. {
  2179. std::istringstream ss(line);
  2180. std::string v;
  2181. vec3 & p = norm.emplace_back();
  2182. ss >> v;
  2183. ss >> p[0];
  2184. ss >> p[1];
  2185. ss >> p[2];
  2186. }
  2187. else if(line[1] == 't')
  2188. {
  2189. std::istringstream ss(line);
  2190. std::string v;
  2191. vec2 & p = uv.emplace_back();
  2192. ss >> v;
  2193. ss >> p[0];
  2194. ss >> p[1];
  2195. }
  2196. else if(line[0] == 'v')
  2197. {
  2198. std::istringstream ss(line);
  2199. std::string v;
  2200. vec3 & p = pos.emplace_back();
  2201. ss >> v;
  2202. ss >> p[0];
  2203. ss >> p[1];
  2204. ss >> p[2];
  2205. }
  2206. else if(line[0] == 'f')
  2207. {
  2208. // f 6/11/6 5/10/6 1/1/6 2/13/6
  2209. // f 6/11/6 5/10/6 1/1/6
  2210. // f 6//6 5//6 1//6
  2211. // f 6 5 1
  2212. std::istringstream ss(line);
  2213. std::string _b;
  2214. ss >> _b; // read the 'f'
  2215. auto _extractVertexID = [](std::string str)
  2216. {
  2217. std::istringstream s(str);
  2218. vertex_id v = {};
  2219. // can either be a/b/c
  2220. // a//c
  2221. // a
  2222. s >> std::get<0>(v);
  2223. if(s.eof())
  2224. return v;
  2225. if(s.peek() == '/')
  2226. {
  2227. s.get();
  2228. }
  2229. if(s.peek() == '/')
  2230. {
  2231. s.get();
  2232. s >> std::get<2>(v);
  2233. }
  2234. else
  2235. {
  2236. s >> std::get<1>(v);
  2237. }
  2238. if(s.peek() == '/')
  2239. {
  2240. s.get();
  2241. s >> std::get<2>(v);
  2242. }
  2243. return v;
  2244. };
  2245. std::array<vertex_id, 4> _faceIndex;
  2246. uint32_t j=0;
  2247. while(!ss.eof())
  2248. {
  2249. std::string vertex_id_str;
  2250. ss >> vertex_id_str;
  2251. if(!vertex_id_str.empty())
  2252. {
  2253. _faceIndex[j++] = _extractVertexID(vertex_id_str);
  2254. // std::cout << std::get<0>(V) << " " << std::get<1>(V) << " " << std::get<2>(V) << std::endl;
  2255. }
  2256. }
  2257. // we now have the verttex'x position index, normal index and uv index
  2258. // in the form of a 3-tuple
  2259. // Insert the tuple into the ma
  2260. if(j==3) // triangle
  2261. {
  2262. tri_face t = { vertex_to_index.insert( {_faceIndex[0], static_cast<uint32_t>(vertex_to_index.size())}).first->second,
  2263. vertex_to_index.insert( {_faceIndex[1], static_cast<uint32_t>(vertex_to_index.size())}).first->second,
  2264. vertex_to_index.insert( {_faceIndex[2], static_cast<uint32_t>(vertex_to_index.size())}).first->second};
  2265. tris.push_back(t);
  2266. }
  2267. if(j==4) // triangle
  2268. {
  2269. quad_face t = { vertex_to_index.insert( {_faceIndex[0], static_cast<uint32_t>(vertex_to_index.size())}).first->second,
  2270. vertex_to_index.insert( {_faceIndex[1], static_cast<uint32_t>(vertex_to_index.size())}).first->second,
  2271. vertex_to_index.insert( {_faceIndex[2], static_cast<uint32_t>(vertex_to_index.size())}).first->second,
  2272. vertex_to_index.insert( {_faceIndex[3], static_cast<uint32_t>(vertex_to_index.size())}).first->second};
  2273. quads.push_back(t);
  2274. }
  2275. // end
  2276. }
  2277. }
  2278. for(auto & t : quads)
  2279. {
  2280. tris.push_back( {t[0], t[1], t[2]});
  2281. tris.push_back( {t[0], t[2], t[3]});
  2282. }
  2283. for(auto & t : tris)
  2284. {
  2285. std::swap(t[0], t[2]);
  2286. }
  2287. // std::cout << "Total Triangles: " << tris.size() << std::endl;
  2288. // std::cout << "Total Vertices: " << pos.size() << std::endl;
  2289. // std::cout << "Total Position values: " << pos.size() << std::endl;
  2290. // std::cout << "Total Normal values: " << norm.size() << std::endl;
  2291. // std::cout << "Total UV values: " << uv.size() << std::endl;
  2292. gul::MeshPrimitive P;
  2293. P.INDEX.setType(gul::eType::SCALAR);
  2294. P.INDEX.setComponent(gul::eComponentType::UNSIGNED_INT);
  2295. P.TEXCOORD_0.setType(gul::eType::VEC2);
  2296. P.TEXCOORD_0.setComponent(gul::eComponentType::FLOAT);
  2297. P.POSITION.setType(gul::eType::VEC3);
  2298. P.POSITION.setComponent(gul::eComponentType::FLOAT);
  2299. P.NORMAL.setType(gul::eType::VEC3);
  2300. P.NORMAL.setComponent(gul::eComponentType::FLOAT);
  2301. P.POSITION.resize(vertex_to_index.size());
  2302. P.TEXCOORD_0.resize(vertex_to_index.size());
  2303. P.NORMAL.resize(vertex_to_index.size());
  2304. for(auto & [v, index] : vertex_to_index)
  2305. {
  2306. if(std::get<0>(v) != 0) P.POSITION.set(index , pos.at( std::get<0>(v)-1) );
  2307. if(std::get<1>(v) != 0) P.TEXCOORD_0.set(index, uv.at( std::get<1>(v)-1) );
  2308. if(std::get<2>(v) != 0) P.NORMAL.set(index , norm.at(std::get<2>(v)-1) );
  2309. }
  2310. if(P.NORMAL.attributeCount() != P.POSITION.attributeCount())
  2311. P.NORMAL = {};
  2312. if(P.TEXCOORD_0.attributeCount() != P.POSITION.attributeCount())
  2313. P.TEXCOORD_0 = {};
  2314. for(auto & t : tris)
  2315. {
  2316. P.INDEX.push_back(t[2]);
  2317. P.INDEX.push_back(t[1]);
  2318. P.INDEX.push_back(t[0]);
  2319. }
  2320. return P;
  2321. }
  2322. }
  2323. #endif