streakRender.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  1. /*
  2. ** Command & Conquer Generals Zero Hour(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /***********************************************************************************************
  19. *** EA PACIFIC CONFIDENTIAL ***
  20. ***********************************************************************************************
  21. * *
  22. * Original Author:: Mark Lorenzen *
  23. * *
  24. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  25. #include "streakrender.h"
  26. #include "ww3d.h"
  27. #include "rinfo.h"
  28. #include "dx8wrapper.h"
  29. #include "sortingrenderer.h"
  30. #include "vp.h"
  31. #include "vector3i.h"
  32. #include "random.h"
  33. #include "v3_rnd.h"
  34. #ifdef _INTERNAL
  35. // for occasional debugging...
  36. // #pragma optimize("", off)
  37. // #pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  38. #endif
  39. /* We have chunking logic which handles N segments at a time. To simplify the subdivision logic,
  40. ** we will ensure that N is a power of two and that N >= 2^MAX_STREAK_SUBDIV_LEVELS, so that the
  41. ** subdivision logic can be inside the chunking loop.
  42. */
  43. #if MAX_STREAK_SUBDIV_LEVELS > 7
  44. #define STREAK_CHUNK_SIZE (1 << MAX_STREAK_SUBDIV_LEVELS)
  45. #else
  46. #define STREAK_CHUNK_SIZE (128)
  47. #endif
  48. #define MAX_STREAK_POINT_BUFFER_SIZE (1 + STREAK_CHUNK_SIZE)
  49. // This macro depends on the assumption that each line segment is two polys.
  50. #define MAX_STREAK_POLY_BUFFER_SIZE (STREAK_CHUNK_SIZE * 2)
  51. StreakRendererClass::StreakRendererClass(void) :
  52. Texture(NULL),
  53. Shader(ShaderClass::_PresetAdditiveSpriteShader),
  54. Width(0.0f),
  55. Color(Vector3(1,1,1)),
  56. Opacity(1.0f),
  57. SubdivisionLevel(0),
  58. NoiseAmplitude(0.0f),
  59. MergeAbortFactor(1.5f),
  60. // TextureTileFactor(1.0f),
  61. // LastUsedSyncTime(WW3D::Get_Sync_Time()),
  62. // CurrentUVOffset(0.0f,0.0f),
  63. // UVOffsetDeltaPerMS(0.0f, 0.0f),
  64. Bits(DEFAULT_BITS),
  65. m_vertexBufferSize(0),
  66. m_vertexBuffer(NULL)
  67. {
  68. // EMPTY
  69. }
  70. StreakRendererClass::StreakRendererClass(const StreakRendererClass & that) :
  71. Texture(NULL),
  72. Shader(ShaderClass::_PresetAdditiveSpriteShader),
  73. Width(0.0f),
  74. Color(Vector3(1,1,1)),
  75. Opacity(1.0f),
  76. SubdivisionLevel(0),
  77. NoiseAmplitude(0.0f),
  78. MergeAbortFactor(1.5f),
  79. // TextureTileFactor(1.0f),
  80. // LastUsedSyncTime(that.LastUsedSyncTime),
  81. // CurrentUVOffset(0.0f,0.0f),
  82. // UVOffsetDeltaPerMS(0.0f, 0.0f),
  83. Bits(DEFAULT_BITS),
  84. m_vertexBufferSize(0),
  85. m_vertexBuffer(NULL)
  86. {
  87. *this = that;
  88. }
  89. StreakRendererClass & StreakRendererClass::operator = (const StreakRendererClass & that)
  90. {
  91. if (this != &that) {
  92. REF_PTR_SET(Texture,that.Texture);
  93. Shader = that.Shader;
  94. Width = that.Width;
  95. Color = that.Color;
  96. Opacity = that.Opacity;
  97. SubdivisionLevel = that.SubdivisionLevel;
  98. NoiseAmplitude = that.NoiseAmplitude;
  99. MergeAbortFactor = that.MergeAbortFactor;
  100. // TextureTileFactor = that.TextureTileFactor;
  101. // LastUsedSyncTime = that.LastUsedSyncTime;
  102. // CurrentUVOffset = that.CurrentUVOffset;
  103. // UVOffsetDeltaPerMS = that.UVOffsetDeltaPerMS;
  104. Bits = that.Bits;
  105. // Don't modify m_vertexBufferSize and m_vertexBuffer.
  106. }
  107. return *this;
  108. }
  109. StreakRendererClass::~StreakRendererClass(void)
  110. {
  111. REF_PTR_RELEASE(Texture);
  112. delete [] m_vertexBuffer;
  113. }
  114. void StreakRendererClass::Init(const W3dEmitterLinePropertiesStruct & props)
  115. {
  116. // translate the flags
  117. Set_Merge_Intersections(props.Flags & W3D_ELINE_MERGE_INTERSECTIONS);
  118. Set_Freeze_Random(props.Flags & W3D_ELINE_FREEZE_RANDOM);
  119. Set_Disable_Sorting(props.Flags & W3D_ELINE_DISABLE_SORTING);
  120. Set_End_Caps(props.Flags & W3D_ELINE_END_CAPS);
  121. int texture_mode = ((props.Flags & W3D_ELINE_TEXTURE_MAP_MODE_MASK) >> W3D_ELINE_TEXTURE_MAP_MODE_OFFSET);
  122. switch (texture_mode)
  123. {
  124. case W3D_ELINE_UNIFORM_WIDTH_TEXTURE_MAP:
  125. Set_Texture_Mapping_Mode(UNIFORM_WIDTH_TEXTURE_MAP);
  126. break;
  127. case W3D_ELINE_UNIFORM_LENGTH_TEXTURE_MAP:
  128. Set_Texture_Mapping_Mode(UNIFORM_LENGTH_TEXTURE_MAP);
  129. break;
  130. case W3D_ELINE_TILED_TEXTURE_MAP:
  131. Set_Texture_Mapping_Mode(TILED_TEXTURE_MAP);
  132. break;
  133. };
  134. // install all other settings
  135. Set_Current_Subdivision_Level(props.SubdivisionLevel);
  136. Set_Noise_Amplitude(props.NoiseAmplitude);
  137. Set_Merge_Abort_Factor(props.MergeAbortFactor);
  138. // Set_Texture_Tile_Factor(props.TextureTileFactor);
  139. // Set_UV_Offset_Rate(Vector2(props.UPerSec,props.VPerSec));
  140. }
  141. void StreakRendererClass::Set_Texture(TextureClass *texture)
  142. {
  143. REF_PTR_SET(Texture,texture);
  144. }
  145. TextureClass * StreakRendererClass::Get_Texture(void) const
  146. {
  147. if (Texture != NULL) {
  148. Texture->Add_Ref();
  149. }
  150. return Texture;
  151. }
  152. // void StreakRendererClass::Set_Current_UV_Offset(const Vector2 & offset)
  153. // {
  154. // CurrentUVOffset = offset;
  155. // }
  156. // void StreakRendererClass::Set_Texture_Tile_Factor(float factor)
  157. // {
  158. // if (factor > 8.0f) {
  159. // factor = 8.0f;
  160. // WWDEBUG_SAY(("Texture Tile Factor too large in StreakRendererClass!\r\n"));
  161. // } else {
  162. // factor = MAX(factor, 0.0f);
  163. // }
  164. // TextureTileFactor = factor;
  165. //}
  166. // void StreakRendererClass::Reset_Line(void)
  167. // {
  168. // LastUsedSyncTime = WW3D::Get_Sync_Time();
  169. // CurrentUVOffset.Set(0.0f,0.0f);
  170. // }
  171. ///////////////////////////////////////////////////////////////////////////////////////////
  172. ///////////////////////////////////////////////////////////////////////////////////////////
  173. void StreakRendererClass::Render
  174. (
  175. RenderInfoClass & rinfo,
  176. const Matrix3D & transform,
  177. unsigned int num_points,
  178. Vector3 * points,
  179. const SphereClass & obj_sphere
  180. )
  181. {
  182. //NOTHING!
  183. return;
  184. }
  185. ///////////////////////////////////////////////////////////////////////////////////////////
  186. ///////////////////////////////////////////////////////////////////////////////////////////
  187. ///////////////////////////////////////////////////////////////////////////////////////////
  188. ///////////////////////////////////////////////////////////////////////////////////////////
  189. void StreakRendererClass::subdivision_util(unsigned int point_cnt, const Vector3 *xformed_pts,
  190. const float *base_tex_v, unsigned int *p_sub_point_cnt, Vector3 *xformed_subdiv_pts,
  191. float *subdiv_tex_v)
  192. {
  193. // CAUTION: freezing the random offsets will make it more readily apparent that the offsets
  194. // are in camera space rather than worldspace.
  195. int freeze_random = Is_Freeze_Random();
  196. Random3Class randomize;
  197. const float oo_int_max = 1.0f / (float)INT_MAX;
  198. Vector3SolidBoxRandomizer randomizer(Vector3(1,1,1));
  199. Vector3 randvec(0,0,0);
  200. unsigned int sub_pointIndex = 0;
  201. struct StreakSubdivision {
  202. Vector3 StartPos;
  203. Vector3 EndPos;
  204. float StartTexV; // V texture coordinate of start point
  205. float EndTexV; // V texture coordinate of end point
  206. float Rand;
  207. unsigned int Level; // Subdivision level
  208. };
  209. StreakSubdivision stack[2 * MAX_STREAK_SUBDIV_LEVELS]; // Maximum number needed
  210. int tos = 0;
  211. for (unsigned int pointIndex = 0; pointIndex < point_cnt - 1; pointIndex++) {
  212. // Subdivide the (pointIndex, pointIndex + 1) segment. Produce pointIndex and all subdivided points up to
  213. // (not including) pointIndex + 1.
  214. tos = 0;
  215. stack[0].StartPos = xformed_pts[pointIndex];
  216. stack[0].EndPos = xformed_pts[pointIndex + 1];
  217. stack[0].StartTexV = base_tex_v[pointIndex];
  218. stack[0].EndTexV = base_tex_v[pointIndex + 1];
  219. stack[0].Rand = NoiseAmplitude;
  220. stack[0].Level = 0;
  221. for (; tos >= 0;) {
  222. if (stack[tos].Level == SubdivisionLevel) {
  223. // Generate point location and texture V coordinate
  224. xformed_subdiv_pts[sub_pointIndex] = stack[tos].StartPos;
  225. subdiv_tex_v[sub_pointIndex++] = stack[tos].StartTexV;
  226. // Pop
  227. tos--;
  228. } else {
  229. // Recurse down: pop existing entry and push two subdivided ones.
  230. if (freeze_random) {
  231. randvec.Set(randomize * oo_int_max, randomize * oo_int_max, randomize * oo_int_max);
  232. } else {
  233. randomizer.Get_Vector(randvec);
  234. }
  235. stack[tos + 1].StartPos = stack[tos].StartPos;
  236. stack[tos + 1].EndPos = (stack[tos].StartPos + stack[tos].EndPos) * 0.5f + randvec * stack[tos].Rand;
  237. stack[tos + 1].StartTexV = stack[tos].StartTexV;
  238. stack[tos + 1].EndTexV = (stack[tos].StartTexV + stack[tos].EndTexV) * 0.5f;
  239. stack[tos + 1].Rand = stack[tos].Rand * 0.5f;
  240. stack[tos + 1].Level = stack[tos].Level + 1;
  241. stack[tos].StartPos = stack[tos + 1].EndPos;
  242. // stack[tos].EndPos already has the right value
  243. stack[tos].StartTexV = stack[tos + 1].EndTexV;
  244. // stack[tos].EndTexV already has the right value
  245. stack[tos].Rand = stack[tos + 1].Rand;
  246. stack[tos].Level = stack[tos + 1].Level;
  247. tos++;
  248. }
  249. }
  250. }
  251. // Last point
  252. xformed_subdiv_pts[sub_pointIndex] = xformed_pts[point_cnt - 1];
  253. subdiv_tex_v[sub_pointIndex++] = base_tex_v[point_cnt - 1];
  254. // Output:
  255. *p_sub_point_cnt = sub_pointIndex;
  256. }
  257. /////// /////// /////// /////// /////// /////// /////// ///////
  258. /////// /////// /////// /////// /////// /////// /////// ///////
  259. /////// /////// /////// /////// /////// /////// /////// ///////
  260. /////// /////// /////// /////// /////// /////// /////// ///////
  261. /////// /////// /////// /////// /////// /////// /////// ///////
  262. /////// /////// /////// /////// /////// /////// /////// ///////
  263. /////// /////// /////// /////// /////// /////// /////// ///////
  264. /////// /////// /////// /////// /////// /////// /////// ///////
  265. /////// /////// /////// /////// /////// /////// /////// ///////
  266. void StreakRendererClass::RenderStreak
  267. (
  268. RenderInfoClass & rinfo,
  269. const Matrix3D & transform,
  270. unsigned int num_points,
  271. Vector3 * points,
  272. Vector4 * colors, /////////////// DIFFERENT FROM RENDER( )
  273. float * widths, /////////////// DIFFERENT FROM RENDER( )
  274. const SphereClass & obj_sphere,
  275. unsigned int *personalities /////////////// DIFFERENT FROM RENDER( )
  276. )
  277. {
  278. Matrix4x4 view;
  279. DX8Wrapper::Get_Transform(D3DTS_VIEW,view);
  280. Matrix4x4 identity(true);
  281. DX8Wrapper::Set_Transform(D3DTS_WORLD,identity);
  282. DX8Wrapper::Set_Transform(D3DTS_VIEW,identity);
  283. /*
  284. ** Handle texture UV offset animation (done once for entire line).
  285. */
  286. // unsigned int delta = WW3D::Get_Sync_Time() - LastUsedSyncTime;
  287. // float del = (float)delta;
  288. //Vector2 uv_offset = CurrentUVOffset + UVOffsetDeltaPerMS * del;
  289. // ensure offsets are in [0, 1] range:
  290. //uv_offset.X = uv_offset.X - floorf(uv_offset.X);
  291. //uv_offset.Y = uv_offset.Y - floorf(uv_offset.Y);
  292. // Update state
  293. //CurrentUVOffset = uv_offset;
  294. // LastUsedSyncTime = WW3D::Get_Sync_Time();
  295. // Used later
  296. TextureMapMode map_mode = Get_Texture_Mapping_Mode();
  297. /*
  298. ** Process line geometry:
  299. */
  300. // This has been tweaked to produce empirically good results.
  301. const float parallel_factor = 0.9f;
  302. // We reduce the chunk size to take account of subdivision levels (so that the # of points
  303. // after subdivision will be no higher than the allowed maximum). We know this will not reduce
  304. // the chunk size below 2, since the chunk size must be at least two to the power of the
  305. // maximum allowable number of subdivisions. The plus 1 is because #points = #segments + 1.
  306. unsigned int chunk_size = (STREAK_CHUNK_SIZE >> SubdivisionLevel) + 1;
  307. if (chunk_size > num_points) chunk_size = num_points;
  308. // Chunk through the points (we increment by chunk_size - 1 because the last point of this
  309. // chunk must be reused as the first point of the next chunk. This is also the reason we stop
  310. // when chunkIndex = NumPoints - 1: the last point has already been processed in the previous
  311. // iteration so we don't need another one).
  312. for (unsigned int chunkIndex = 0; chunkIndex < num_points - 1; chunkIndex += (chunk_size - 1))
  313. {
  314. unsigned int point_cnt = num_points - chunkIndex;
  315. point_cnt = MIN(point_cnt, chunk_size);
  316. // We use these different loop indices (which loop INSIDE a chunk) to improve readability:
  317. unsigned int pointIndex; // Point index
  318. unsigned int segmentIndex; // Segment index
  319. unsigned int intersectionIndex; // Intersection index
  320. /*
  321. ** Transform points in chunk from objectspace to eyespace:
  322. */
  323. Vector3 xformed_pts[MAX_STREAK_POINT_BUFFER_SIZE];
  324. Matrix3D view2( view[0].X,view[0].Y,view[0].Z,view[0].W,
  325. view[1].X,view[1].Y,view[1].Z,view[1].W,
  326. view[2].X,view[2].Y,view[2].Z,view[2].W);
  327. #ifdef ALLOW_TEMPORARIES
  328. Matrix3D modelview=view2*transform;
  329. #else
  330. Matrix3D modelview;
  331. modelview.mul(view2, transform);
  332. #endif
  333. VectorProcessorClass::Transform(&xformed_pts[0],
  334. &points[chunkIndex], modelview, point_cnt);
  335. /*
  336. ** Prepare v parameter per point - used for texture mapping (esp. tiled mapping mode)
  337. */
  338. float base_tex_v[MAX_STREAK_POINT_BUFFER_SIZE];
  339. float u_values[2];
  340. // I HAVE HARD CODED IT TO USE UNIFORM WIDTH AND LENGTH
  341. for (pointIndex = 0; pointIndex < point_cnt; pointIndex++)
  342. {
  343. // All 0
  344. base_tex_v[pointIndex] = 0.0f;
  345. }
  346. u_values[0] = 0.0f;
  347. u_values[1] = 1.0f;
  348. // switch (map_mode)
  349. // {
  350. // case UNIFORM_WIDTH_TEXTURE_MAP:// only non-dead case
  351. // for (pointIndex = 0; pointIndex < point_cnt; pointIndex++)
  352. // {
  353. // // All 0
  354. // base_tex_v[pointIndex] = 0.0f;
  355. // }
  356. // u_values[0] = 0.0f;
  357. // u_values[1] = 1.0f;
  358. // break;
  359. // case UNIFORM_LENGTH_TEXTURE_MAP:
  360. // for (pointIndex = 0; pointIndex < point_cnt; pointIndex++)
  361. // {
  362. // // Increasing V
  363. // base_tex_v[pointIndex] = (float)(pointIndex + chunkIndex) * TextureTileFactor;
  364. // }
  365. // u_values[0] = 0.0f;
  366. // u_values[1] = 0.0f;
  367. // break;
  368. // case TILED_TEXTURE_MAP:
  369. // for (pointIndex = 0; pointIndex < point_cnt; pointIndex++)
  370. // {
  371. // // Increasing V
  372. // base_tex_v[pointIndex] = (float)(pointIndex + chunkIndex) * TextureTileFactor;
  373. // }
  374. // u_values[0] = 0.0f;
  375. // u_values[1] = 1.0f;
  376. // break;
  377. // }
  378. /*
  379. ** Fractal noise recursive subdivision:
  380. ** We find the midpoint for each section, apply a random offset, and recurse. We also find
  381. ** the average V coordinate of the endpoints which is the midpoint V (for tiled texture
  382. ** mapping).
  383. */
  384. Vector3 xformed_subdiv_pts[MAX_STREAK_POINT_BUFFER_SIZE];
  385. float subdiv_tex_v[MAX_STREAK_POINT_BUFFER_SIZE];
  386. unsigned int sub_point_cnt;
  387. subdivision_util(point_cnt, xformed_pts, base_tex_v, &sub_point_cnt, xformed_subdiv_pts, subdiv_tex_v);
  388. // Start using subdivided points from now on
  389. Vector3 *points = xformed_subdiv_pts;
  390. float *tex_v = subdiv_tex_v;
  391. point_cnt = sub_point_cnt;
  392. /*
  393. ** Calculate line segment edge planes:
  394. */
  395. // For each line segment find the two silhouette planes from eyepoint to the line segment
  396. // cylinder. To simplify we do not find the tangent planes but intersect the cylinder with a
  397. // plane passing through its axis and perpendicular to the eye vector, find the edges of the
  398. // resulting rectangle, and create planes through these edges and the eyepoint.
  399. // Note that these planes are represented as a single normal rather than a normal and a
  400. // distance; this is because they pass through the origin (eyepoint) so their distance is
  401. // always zero.
  402. // Since the line has thickness, each segment has two edges. We name these 'top' and
  403. // 'bottom' - note however that the top/bottom distinction does not relate to screen
  404. // up/down and remains consistent throughout the segmented line.
  405. enum SegmentEdge
  406. {
  407. FIRST_EDGE = 0, // For loop conditions
  408. TOP_EDGE = 0, // Top Edge
  409. BOTTOM_EDGE = 1, // Bottom Edge
  410. MAX_EDGE = 1, // For loop conditions
  411. NUM_EDGES = 2 // For array allocations
  412. };
  413. bool switch_edges = false;
  414. // We have dummy segments for "before the first point" and "after the last point" - in these
  415. // segments the top and bottom edge are the same - they are a perpendicular plane defined by
  416. // the endpoint vertices. This is so we can merge intersections properly for the first and
  417. // last points.
  418. struct LineSegment
  419. {
  420. Vector3 StartPlane;
  421. Vector3 EdgePlane[NUM_EDGES];
  422. };
  423. // # segments = numpoints + 1 (numpoints - 1, plus two dummy segments)
  424. LineSegment segment[MAX_STREAK_POINT_BUFFER_SIZE + 1];
  425. // Intersections. This has data for two edges (top or bottom) intersecting.
  426. struct LineSegmentIntersection
  427. {
  428. unsigned int PointCount; // How many points does this intersection represent
  429. unsigned int NextSegmentID; // ID of segment after this intersection
  430. Vector3 Direction; // Calculated intersection direction line
  431. Vector3 Point; // Averaged 3D point on the line which this represents
  432. float TexV; // Averaged texture V coordinate of points
  433. bool Fold; // Does the line fold over at this intersection?
  434. bool Parallel; // Edges at this intersection are parallel (or almost-)
  435. };
  436. // Used to calculate the edge planes
  437. float radius = Width * 0.5f;
  438. // The number of intersections is the number of points minus 2. However, we store
  439. // intersection records for the first and last point, even though they are not really
  440. // intersections. The reason we do this is for the intersection merging - the vertices for
  441. // the first and last points can get merged just like any other intersection. Also, we have
  442. // a dummy intersection record before the first point - this is because we want "previous
  443. // segments" for the first point and each intersection only has an index for the next
  444. // segment.
  445. LineSegmentIntersection intersection[MAX_STREAK_POINT_BUFFER_SIZE + 1][NUM_EDGES];
  446. for (segmentIndex = 1; segmentIndex < point_cnt; segmentIndex++)
  447. { // #segments = #points - 1 (+ 2 dummy segments)
  448. radius = widths[segmentIndex]; /// NEW ///// // TODO: Does not work correctly when subdivision are not 0
  449. Vector3 &curr_point = points[segmentIndex - 1];
  450. Vector3 &next_point = points[segmentIndex];
  451. if (Equal_Within_Epsilon(curr_point, next_point, 0.0001f))
  452. {
  453. next_point.X += 0.001f;
  454. }
  455. // We temporarily store the segment direction in the segment's StartPlane (since it is
  456. // used to calculate the StartPlane later).
  457. Vector3 &segdir = segment[segmentIndex].StartPlane;
  458. segdir = next_point - curr_point;
  459. segdir.Normalize();
  460. // Find nearest point on infinite line to eye (origin)
  461. Vector3 nearest = curr_point + segdir * -Vector3::Dot_Product(segdir, curr_point);
  462. // Find top and bottom points on cylinder
  463. Vector3 offset;
  464. Vector3::Cross_Product(segdir, nearest, &offset);
  465. offset.Normalize();
  466. Vector3 top = curr_point + offset * radius;
  467. Vector3 bottom = curr_point + offset * -radius;
  468. // Find planes through top/bottom points and eyepoint. In addition to the two points, we
  469. // know that the planes are parallel to the line segment.
  470. Vector3 top_normal;
  471. Vector3::Cross_Product(top, segdir, &top_normal);
  472. top_normal.Normalize();
  473. segment[segmentIndex].EdgePlane[TOP_EDGE] = top_normal;
  474. Vector3 bottom_normal;
  475. Vector3::Cross_Product(segdir, bottom, &bottom_normal);
  476. bottom_normal.Normalize();
  477. segment[segmentIndex].EdgePlane[BOTTOM_EDGE] = bottom_normal;
  478. // If the visual angle between the previous and current line segments (we use the angle
  479. // between the planes defined by each line segment and the eyepoint) is less than 90
  480. // degrees, switch the top and bottom edges for the current and subsequent segments and
  481. // mark the intersection as having a fold
  482. if (segmentIndex > 1)
  483. {
  484. Vector3 prev_plane;
  485. Vector3::Cross_Product(points[segmentIndex - 2], curr_point, &prev_plane);
  486. prev_plane.Normalize();
  487. Vector3 curr_plane;
  488. Vector3::Cross_Product(curr_point, next_point, &curr_plane);
  489. curr_plane.Normalize();
  490. if (Vector3::Dot_Product(prev_plane, curr_plane) < 0.0f)
  491. {
  492. switch_edges = !switch_edges;
  493. intersection[segmentIndex][TOP_EDGE].Fold = true;
  494. intersection[segmentIndex][BOTTOM_EDGE].Fold = true;
  495. }
  496. else
  497. {
  498. intersection[segmentIndex][TOP_EDGE].Fold = false;
  499. intersection[segmentIndex][BOTTOM_EDGE].Fold = false;
  500. }
  501. }
  502. if (switch_edges)
  503. {
  504. // We switch signs so the normals will always point inwards
  505. segment[segmentIndex].EdgePlane[TOP_EDGE] = -bottom_normal;
  506. segment[segmentIndex].EdgePlane[BOTTOM_EDGE] = -top_normal;
  507. }
  508. }
  509. // The two dummy segments for the clipping edges of the first and last real segments will be
  510. // defined later, with the first and last intersections.
  511. /*
  512. ** Calculate segment edge intersections:
  513. */
  514. unsigned int numsegs = point_cnt - 1; // Doesn't include the two dummy segments
  515. unsigned int num_intersections[NUM_EDGES];
  516. // These include the 1st, last point "intersections", not the pre-first dummy intersection
  517. num_intersections[TOP_EDGE] = point_cnt;
  518. num_intersections[BOTTOM_EDGE] = point_cnt;
  519. // Initialize pre-first point dummy intersection record (only NextSegmentID will be used).
  520. intersection[0][TOP_EDGE].PointCount = 0; // Should never be used
  521. intersection[0][TOP_EDGE].NextSegmentID = 0; // Points to first dummy segment
  522. intersection[0][TOP_EDGE].Direction.Set(1,0,0); // Should never be used
  523. intersection[0][TOP_EDGE].Point.Set(0,0,0); // Should never be used
  524. intersection[0][TOP_EDGE].TexV = 0.0f; // Should never be used
  525. intersection[0][TOP_EDGE].Fold = true; // Should never be used
  526. intersection[0][TOP_EDGE].Parallel = false; // Should never be used
  527. intersection[0][BOTTOM_EDGE].PointCount = 0; // Should never be used
  528. intersection[0][BOTTOM_EDGE].NextSegmentID = 0; // Points to first dummy segment
  529. intersection[0][BOTTOM_EDGE].Point.Set(0,0,0); // Should never be used
  530. intersection[0][BOTTOM_EDGE].TexV = 0.0f; // Should never be used
  531. intersection[0][BOTTOM_EDGE].Direction.Set(1,0,0); // Should never be used
  532. intersection[0][BOTTOM_EDGE].Fold = true; // Should never be used
  533. intersection[0][BOTTOM_EDGE].Parallel = false; // Should never be used
  534. // Initialize first point "intersection" record.
  535. intersection[1][TOP_EDGE].PointCount = 1;
  536. intersection[1][TOP_EDGE].NextSegmentID = 1;
  537. intersection[1][TOP_EDGE].Point = points[0];
  538. intersection[1][TOP_EDGE].TexV = tex_v[0];
  539. intersection[1][TOP_EDGE].Fold = true;
  540. intersection[1][TOP_EDGE].Parallel = false;
  541. intersection[1][BOTTOM_EDGE].PointCount = 1;
  542. intersection[1][BOTTOM_EDGE].NextSegmentID = 1;
  543. intersection[1][BOTTOM_EDGE].Point = points[0];
  544. intersection[1][BOTTOM_EDGE].TexV = tex_v[0];
  545. intersection[1][BOTTOM_EDGE].Fold = true;
  546. intersection[1][BOTTOM_EDGE].Parallel = false;
  547. // Find closest point to 1st top/bottom segment edge plane, and convert to direction vector
  548. // and dummy segment edge plane.
  549. Vector3 top;
  550. Vector3 bottom;
  551. Vector3 &first_point = points[0];
  552. Vector3 *first_plane = &(segment[1].EdgePlane[0]);
  553. top = first_point - first_plane[TOP_EDGE] * Vector3::Dot_Product(first_plane[TOP_EDGE], first_point);
  554. top.Normalize();
  555. intersection[1][TOP_EDGE].Direction = top;
  556. bottom = first_point - first_plane[BOTTOM_EDGE] * Vector3::Dot_Product(first_plane[BOTTOM_EDGE], first_point);
  557. bottom.Normalize();
  558. intersection[1][BOTTOM_EDGE].Direction = bottom;
  559. Vector3 segdir = points[1] - points[0];
  560. segdir.Normalize(); // Is this needed? Probably not - remove later when all works
  561. Vector3 start_pl;
  562. Vector3::Cross_Product(top, bottom, &start_pl);
  563. start_pl.Normalize();
  564. float dp = Vector3::Dot_Product(segdir, start_pl);
  565. if (dp > 0.0f)
  566. {
  567. segment[0].StartPlane = segment[0].EdgePlane[TOP_EDGE] = segment[0].EdgePlane[BOTTOM_EDGE] = start_pl;
  568. }
  569. else
  570. {
  571. segment[0].StartPlane = segment[0].EdgePlane[TOP_EDGE] = segment[0].EdgePlane[BOTTOM_EDGE] = -start_pl;
  572. }
  573. // Initialize StartPlane for the first "real" segment
  574. segment[1].StartPlane = segment[0].StartPlane;
  575. // Initialize last point "intersection" record.
  576. unsigned int last_isec = num_intersections[TOP_EDGE]; // Same # top, bottom intersections
  577. intersection[last_isec][TOP_EDGE].PointCount = 1;
  578. intersection[last_isec][TOP_EDGE].NextSegmentID = numsegs + 1; // Last dummy segment
  579. intersection[last_isec][TOP_EDGE].Point = points[point_cnt - 1];
  580. intersection[last_isec][TOP_EDGE].TexV = tex_v[point_cnt - 1];
  581. intersection[last_isec][TOP_EDGE].Fold = true;
  582. intersection[last_isec][TOP_EDGE].Parallel = false;
  583. intersection[last_isec][BOTTOM_EDGE].PointCount = 1;
  584. intersection[last_isec][BOTTOM_EDGE].NextSegmentID = numsegs + 1;// Last dummy segment
  585. intersection[last_isec][BOTTOM_EDGE].Point = points[point_cnt - 1];
  586. intersection[last_isec][BOTTOM_EDGE].TexV = tex_v[point_cnt - 1];
  587. intersection[last_isec][BOTTOM_EDGE].Fold = true;
  588. intersection[last_isec][BOTTOM_EDGE].Parallel = false;
  589. // Find closest point to last top/bottom segment edge plane, and convert to direction vector
  590. // and dummy segment edge vector
  591. Vector3 &last_point = points[point_cnt - 1];
  592. Vector3 *last_plane = &(segment[numsegs].EdgePlane[0]);
  593. top = last_point - last_plane[TOP_EDGE] * Vector3::Dot_Product(last_plane[TOP_EDGE], last_point);
  594. top.Normalize();
  595. intersection[last_isec][TOP_EDGE].Direction = top;
  596. bottom = last_point - last_plane[BOTTOM_EDGE] * Vector3::Dot_Product(last_plane[BOTTOM_EDGE], last_point);
  597. bottom.Normalize();
  598. intersection[last_isec][BOTTOM_EDGE].Direction = bottom;
  599. segdir = points[point_cnt - 1] - points[point_cnt - 2];
  600. segdir.Normalize(); // Is this needed? Probably not - remove later when all works
  601. Vector3::Cross_Product(top, bottom, &start_pl);
  602. start_pl.Normalize();
  603. dp = Vector3::Dot_Product(segdir, start_pl);
  604. if (dp > 0.0f)
  605. {
  606. segment[numsegs + 1].StartPlane = segment[numsegs + 1].EdgePlane[TOP_EDGE] =
  607. segment[numsegs + 1].EdgePlane[BOTTOM_EDGE] = start_pl;
  608. }
  609. else
  610. {
  611. segment[numsegs + 1].StartPlane = segment[numsegs + 1].EdgePlane[TOP_EDGE] =
  612. segment[numsegs + 1].EdgePlane[BOTTOM_EDGE] = -start_pl;
  613. }
  614. // Calculate midpoint segment intersections. There are 2 segment intersections for each
  615. // point: top and bottom (due to the fact that the segments have width, so they have a top
  616. // edge and a bottom edge). Note that the top/bottom distinction does not relate to screen
  617. // up/down. Since each segment edge is represented by a plane passing through the origin
  618. // (eyepoint), the intersection of two such is a line passing through the origin, which is
  619. // represented as a normalized direction vector.
  620. // We use both segment intersections to define the startplane for the segment which begins
  621. // at that intersection.
  622. float vdp;
  623. for (intersectionIndex = 2; intersectionIndex < num_intersections[TOP_EDGE]; intersectionIndex++)
  624. {
  625. // Relevant midpoint:
  626. Vector3 &midpoint = points[intersectionIndex - 1];
  627. float mid_tex_v = tex_v[intersectionIndex - 1];
  628. // Initialize misc. fields
  629. intersection[intersectionIndex][TOP_EDGE].PointCount = 1;
  630. intersection[intersectionIndex][TOP_EDGE].NextSegmentID = intersectionIndex;
  631. intersection[intersectionIndex][TOP_EDGE].Point = midpoint;
  632. // intersection[intersectionIndex][TOP_EDGE].TexV = mid_tex_v;
  633. intersection[intersectionIndex][TOP_EDGE].TexV = personalities[intersectionIndex]&1;//LORENZEN LORENZEN
  634. intersection[intersectionIndex][BOTTOM_EDGE].PointCount = 1;
  635. intersection[intersectionIndex][BOTTOM_EDGE].NextSegmentID = intersectionIndex;
  636. intersection[intersectionIndex][BOTTOM_EDGE].Point = midpoint;
  637. // intersection[intersectionIndex][BOTTOM_EDGE].TexV = mid_tex_v;
  638. intersection[intersectionIndex][BOTTOM_EDGE].TexV = personalities[intersectionIndex]&1;//LORENZEN LORENZEN
  639. // Intersection calculation: if the top/bottom planes of both adjoining segments are not
  640. // very close to being parallel, intersect them to get top/bottom intersection lines. If
  641. // the planes are almost parallel, pick one, find the point on the plane closest to the
  642. // midpoint, and convert that point to a line direction vector.
  643. // Top:
  644. vdp = Vector3::Dot_Product(segment[intersectionIndex - 1].EdgePlane[TOP_EDGE], segment[intersectionIndex].EdgePlane[TOP_EDGE]);
  645. if (fabs(vdp) < parallel_factor)
  646. {
  647. // Not parallel - intersect planes to get line (get vector, normalize it, ensure it is
  648. // pointing towards the midpoint)
  649. Vector3::Cross_Product(segment[intersectionIndex - 1].EdgePlane[TOP_EDGE], segment[intersectionIndex].EdgePlane[TOP_EDGE],
  650. &(intersection[intersectionIndex][TOP_EDGE].Direction));
  651. intersection[intersectionIndex][TOP_EDGE].Direction.Normalize();
  652. if (Vector3::Dot_Product(intersection[intersectionIndex][TOP_EDGE].Direction, midpoint) < 0.0f)
  653. {
  654. intersection[intersectionIndex][TOP_EDGE].Direction = -intersection[intersectionIndex][TOP_EDGE].Direction;
  655. }
  656. intersection[intersectionIndex][TOP_EDGE].Parallel = false;
  657. }
  658. else
  659. {
  660. // Parallel (or almost): find point on av. plane closest to midpoint, convert to line
  661. // Ensure average calculation is numerically stable:
  662. Vector3 pl;
  663. if (vdp > 0.0f)
  664. {
  665. pl = segment[intersectionIndex - 1].EdgePlane[TOP_EDGE] + segment[intersectionIndex].EdgePlane[TOP_EDGE];
  666. }
  667. else
  668. {
  669. pl = segment[intersectionIndex - 1].EdgePlane[TOP_EDGE] - segment[intersectionIndex].EdgePlane[TOP_EDGE];
  670. }
  671. pl.Normalize();
  672. intersection[intersectionIndex][TOP_EDGE].Direction = midpoint - pl * Vector3::Dot_Product(pl, midpoint);
  673. intersection[intersectionIndex][TOP_EDGE].Direction.Normalize();
  674. intersection[intersectionIndex][TOP_EDGE].Parallel = true;
  675. }
  676. // Bottom:
  677. vdp = Vector3::Dot_Product(segment[intersectionIndex - 1].EdgePlane[BOTTOM_EDGE], segment[intersectionIndex].EdgePlane[BOTTOM_EDGE]);
  678. if (fabs(vdp) < parallel_factor)
  679. {
  680. // Not parallel - intersect planes to get line (get vector, normalize it, ensure it is
  681. // pointing towards the midpoint)
  682. Vector3::Cross_Product(segment[intersectionIndex - 1].EdgePlane[BOTTOM_EDGE], segment[intersectionIndex].EdgePlane[BOTTOM_EDGE],
  683. &(intersection[intersectionIndex][BOTTOM_EDGE].Direction));
  684. intersection[intersectionIndex][BOTTOM_EDGE].Direction.Normalize();
  685. if (Vector3::Dot_Product(intersection[intersectionIndex][BOTTOM_EDGE].Direction, midpoint) < 0.0f)
  686. {
  687. intersection[intersectionIndex][BOTTOM_EDGE].Direction = -intersection[intersectionIndex][BOTTOM_EDGE].Direction;
  688. }
  689. intersection[intersectionIndex][BOTTOM_EDGE].Parallel = false;
  690. }
  691. else
  692. {
  693. // Parallel (or almost): find point on av. plane closest to midpoint, convert to line
  694. // Ensure average calculation is numerically stable:
  695. Vector3 pl;
  696. if (vdp > 0.0f)
  697. {
  698. pl = segment[intersectionIndex - 1].EdgePlane[BOTTOM_EDGE] + segment[intersectionIndex].EdgePlane[BOTTOM_EDGE];
  699. }
  700. else
  701. {
  702. pl = segment[intersectionIndex - 1].EdgePlane[BOTTOM_EDGE] - segment[intersectionIndex].EdgePlane[BOTTOM_EDGE];
  703. }
  704. pl.Normalize();
  705. intersection[intersectionIndex][BOTTOM_EDGE].Direction = midpoint - pl * Vector3::Dot_Product(pl, midpoint);
  706. intersection[intersectionIndex][BOTTOM_EDGE].Direction.Normalize();
  707. intersection[intersectionIndex][BOTTOM_EDGE].Parallel = true;
  708. }
  709. // Find StartPlane:
  710. Vector3::Cross_Product(intersection[intersectionIndex][TOP_EDGE].Direction, intersection[intersectionIndex][BOTTOM_EDGE].Direction, &start_pl);
  711. start_pl.Normalize();
  712. dp = Vector3::Dot_Product(segment[intersectionIndex].StartPlane, start_pl);
  713. if (dp > 0.0f)
  714. {
  715. segment[intersectionIndex].StartPlane = start_pl;
  716. }
  717. else
  718. {
  719. segment[intersectionIndex].StartPlane = -start_pl;
  720. }
  721. } // for intersectionIndex
  722. /*
  723. ** Intersection merging: when an intersection is inside an adjacent segment and certain
  724. ** other conditions hold true, we need to merge intersections to avoid visual glitches
  725. ** caused by the polys folding over on themselves.
  726. */
  727. if (Is_Merge_Intersections())
  728. {
  729. // Since we are merging the intersections in-place, we have two index variables, a "read
  730. // index" and a "write index".
  731. unsigned int intersectionIndex_r;
  732. unsigned int intersectionIndex_w;
  733. // The merges will be repeated in multiple passes until none are performed. The reason
  734. // for this is that one merge may cause the need for another merge elsewhere.
  735. bool merged = true;
  736. while (merged)
  737. {
  738. merged = false;
  739. SegmentEdge edge;
  740. for (edge = FIRST_EDGE; edge <= MAX_EDGE; edge = (SegmentEdge)((int)edge + 1))
  741. {
  742. // Merge top and bottom edge intersections: loop through the intersections from the
  743. // first intersection to the penultimate intersection, for each intersection check
  744. // if it needs to be merged with the next one (which is why the loop doesn't go all
  745. // the way to the last intersection). We start at 1 because 0 is the dummy
  746. // "pre-first-point" intersection.
  747. unsigned int num_isects = num_intersections[edge]; // Capture here because will change inside loop
  748. for (intersectionIndex_r = 1, intersectionIndex_w = 1; intersectionIndex_r < num_isects; intersectionIndex_r++, intersectionIndex_w++) {
  749. // Check for either of two possible reasons to merge this intersection with the
  750. // next: either the segment on the far side of the next intersection overlaps
  751. // this intersection, or the previous segment overlaps the next intersection.
  752. // Note that some other conditions need to be true as well.
  753. // Note: intersectionIndex_r is used for anything at or after the current position, intersectionIndex_w is
  754. // used for anything before the current position (previous positions have
  755. // potentially already been merged).
  756. // Note: intersectionIndex_r is used for anything at or after the current position, intersectionIndex_w is
  757. // used for anything before the current position (previous positions have
  758. // potentially already been merged).
  759. LineSegmentIntersection *curr_int = &(intersection[intersectionIndex_r][edge]);
  760. LineSegmentIntersection *next_int = &(intersection[intersectionIndex_r + 1][edge]);
  761. LineSegmentIntersection *write_int = &(intersection[intersectionIndex_w][edge]);
  762. LineSegmentIntersection *prev_int = &(intersection[intersectionIndex_w - 1][edge]);
  763. LineSegment *next_seg = &(segment[next_int->NextSegmentID]);
  764. LineSegment *curr_seg = &(segment[curr_int->NextSegmentID]);
  765. LineSegment *prev_seg = &(segment[prev_int->NextSegmentID]);
  766. // If this intersection is inside both the start plane and the segment edge
  767. // plane of the segment after the next intersection, merge this edge
  768. // intersection and the next. We repeat merging until no longer needed.
  769. // NOTE - we do not merge across a fold.
  770. while ( (!next_int->Fold &&
  771. (Vector3::Dot_Product(curr_int->Direction, next_seg->StartPlane) > 0.0f) &&
  772. (Vector3::Dot_Product(curr_int->Direction, next_seg->EdgePlane[edge]) > 0.0f )) ||
  773. (!curr_int->Fold &&
  774. (Vector3::Dot_Product(next_int->Direction, -curr_seg->StartPlane) > 0.0f) &&
  775. (Vector3::Dot_Product(next_int->Direction, prev_seg->EdgePlane[edge]) > 0.0f )) )
  776. {
  777. // First calculate location of merged intersection - this is so we can abort
  778. // the merge if it yields funky results.
  779. // Find mean point (weighted so all points have same weighting)
  780. unsigned int new_count = curr_int->PointCount + next_int->PointCount;
  781. float oo_new_count = 1.0f / (float)new_count;
  782. float curr_factor = oo_new_count * (float)curr_int->PointCount;
  783. float next_factor = oo_new_count * (float)curr_int->PointCount;
  784. Vector3 new_point = curr_int->Point * curr_factor + next_int->Point * next_factor;
  785. float new_tex_v = curr_int->TexV * curr_factor + next_int->TexV * next_factor;
  786. // Calculate new intersection direction by intersecting prev_seg with next_seg
  787. bool new_parallel;
  788. Vector3 new_direction;
  789. vdp = Vector3::Dot_Product(prev_seg->EdgePlane[edge], next_seg->EdgePlane[edge]);
  790. if (fabs(vdp) < parallel_factor)
  791. {
  792. // Not parallel - intersect planes to get line (get vector, normalize it,
  793. // ensure it is pointing towards the current point)
  794. Vector3::Cross_Product(prev_seg->EdgePlane[edge], next_seg->EdgePlane[edge], &new_direction);
  795. new_direction.Normalize();
  796. if (Vector3::Dot_Product(new_direction, new_point) < 0.0f)
  797. {
  798. new_direction = -new_direction;
  799. }
  800. new_parallel = false;
  801. }
  802. else
  803. {
  804. // Parallel (or almost). If the current intersection is not parallel, take
  805. // the average plane and intersect it with the skipped plane. If the
  806. // current intersection is parallel, find the average plane, and find the
  807. // direction vector on it closest to the current intersections direction
  808. // vector.
  809. // Ensure average calculation is numerically stable:
  810. Vector3 pl;
  811. if (vdp > 0.0f)
  812. {
  813. pl = prev_seg->EdgePlane[edge] + next_seg->EdgePlane[edge];
  814. }
  815. else
  816. {
  817. pl = prev_seg->EdgePlane[edge] - next_seg->EdgePlane[edge];
  818. }
  819. pl.Normalize();
  820. if (curr_int->Parallel)
  821. {
  822. new_direction = new_direction - pl * Vector3::Dot_Product(pl, new_direction);
  823. new_direction.Normalize();
  824. }
  825. else
  826. {
  827. Vector3::Cross_Product(curr_seg->EdgePlane[edge], pl, &new_direction);
  828. new_direction.Normalize();
  829. }
  830. new_parallel = true;
  831. }
  832. // Now check to see if the merge caused any funky results - if so abort it.
  833. // Currently we check to see if the distance of the direction from the two
  834. // points is larger than the radius times the merge_abort factor.
  835. if (MergeAbortFactor > 0.0f)
  836. {
  837. float abort_dist = radius * MergeAbortFactor;
  838. float abort_dist2 = abort_dist * abort_dist;
  839. Vector3 diff_curr = curr_int->Point -
  840. new_direction * Vector3::Dot_Product(curr_int->Point, new_direction);
  841. if (diff_curr.Length2() > abort_dist2) break;
  842. Vector3 next_curr = next_int->Point -
  843. new_direction * Vector3::Dot_Product(next_int->Point, new_direction);
  844. if (next_curr.Length2() > abort_dist2) break;
  845. }
  846. // Merge edge intersections (curr_int and next_int) into curr_int
  847. merged = true;
  848. curr_int->Direction = new_direction;
  849. curr_int->Parallel = new_parallel;
  850. curr_int->Point = new_point;
  851. curr_int->TexV = new_tex_v;
  852. curr_int->PointCount = new_count;
  853. curr_int->NextSegmentID = next_int->NextSegmentID;
  854. curr_int->Fold = curr_int->Fold || next_int->Fold;
  855. // Decrement number of edge intersections
  856. num_intersections[edge]--;
  857. // Advance intersectionIndex_r to shift subsequent entries backwards in result.
  858. intersectionIndex_r++;
  859. // If we are at the end then break:
  860. if (intersectionIndex_r == num_isects)
  861. {
  862. break;
  863. }
  864. // Advance next_int and next_seg.
  865. next_int = &(intersection[intersectionIndex_r + 1][edge]);
  866. next_seg = &(segment[next_int->NextSegmentID]);
  867. } // while <merging needed>
  868. // Copy from "read index" to "write index"
  869. write_int->PointCount = curr_int->PointCount;
  870. write_int->NextSegmentID = curr_int->NextSegmentID;
  871. write_int->Point = curr_int->Point;
  872. write_int->TexV = curr_int->TexV;
  873. write_int->Direction = curr_int->Direction;
  874. write_int->Fold = curr_int->Fold;
  875. } // for intersectionIndex
  876. // If intersectionIndex_r is exactly equal to num_isects (rather than being larger by one) at this
  877. // point, this means that the last intersection was not merged with the previous one. In
  878. // this case, we need to do one last copy:
  879. if (intersectionIndex_r == num_isects)
  880. {
  881. LineSegmentIntersection *write_int = &(intersection[intersectionIndex_w][edge]);
  882. LineSegmentIntersection *curr_int = &(intersection[intersectionIndex_r][edge]);
  883. write_int->PointCount = curr_int->PointCount;
  884. write_int->NextSegmentID = curr_int->NextSegmentID;
  885. write_int->Point = curr_int->Point;
  886. write_int->TexV = curr_int->TexV;
  887. write_int->Direction = curr_int->Direction;
  888. write_int->Fold = curr_int->Fold;
  889. }
  890. #ifdef ENABLE_WWDEBUGGING
  891. // Testing code - ensure total PointCount fits the number of points
  892. unsigned int total_cnt = 0;
  893. for (unsigned int nidx = 0; nidx <= num_intersections[edge]; nidx++)
  894. {
  895. total_cnt += intersection[nidx][edge].PointCount;
  896. }
  897. assert(total_cnt == point_cnt);
  898. #endif
  899. } // for edge
  900. } // while (merged)
  901. } // if (Is_Merge_Intersections())
  902. /*
  903. ** Find vertex positions, generate vertices and triangles:
  904. ** Since we can have top/bottom intersections merged, we need to skip points if both the top
  905. ** and bottom intersections are merged, generate triangle fans if one of the sides is merged
  906. ** and the other isnt, and generate triangle strips otherwise.
  907. */
  908. // Configure vertex array and setup renderer.
  909. unsigned int vnum = num_intersections[TOP_EDGE] + num_intersections[BOTTOM_EDGE];
  910. VertexFormatXYZUV1 *vertexArray = getVertexBuffer(vnum);
  911. Vector3i v_index_array[MAX_STREAK_POLY_BUFFER_SIZE];
  912. // Vertex and triangle indices
  913. unsigned int vertexIndex = 0;
  914. unsigned int triangleIndex = 0;
  915. // GENERALIZE FOR WHEN NO TEXTURE (DO NOT SET UV IN THESE CASES? NEED TO GENERALIZE FOR DIFFERENT TEXTURING MODES ANYWAY).
  916. // "Prime the pump" with two vertices (pick nearest point on each direction line):
  917. Vector3 &top_dir = intersection[1][TOP_EDGE].Direction;
  918. top = top_dir * Vector3::Dot_Product(points[0], top_dir);
  919. Vector3 &bottom_dir = intersection[1][BOTTOM_EDGE].Direction;
  920. bottom = bottom_dir * Vector3::Dot_Product(points[0], bottom_dir);
  921. vertexArray[vertexIndex].x = top.X;
  922. vertexArray[vertexIndex].y = top.Y;
  923. vertexArray[vertexIndex].z = top.Z;
  924. vertexArray[vertexIndex].u1 = u_values[0] ;
  925. vertexArray[vertexIndex].v1 = intersection[1][TOP_EDGE].TexV ;
  926. vertexIndex++;
  927. vertexArray[vertexIndex].x = bottom.X;
  928. vertexArray[vertexIndex].y = bottom.Y;
  929. vertexArray[vertexIndex].z = bottom.Z;
  930. vertexArray[vertexIndex].u1 = u_values[1] ;
  931. vertexArray[vertexIndex].v1 = intersection[1][BOTTOM_EDGE].TexV ;
  932. vertexIndex++;
  933. unsigned int last_top_vertexIndex = 0;
  934. unsigned int last_bottom_vertexIndex = 1;
  935. // Loop over intersections, create new vertices and triangles.
  936. unsigned int top_int_idx = 1; // Skip "pre-first-point" dummy intersection
  937. unsigned int bottom_int_idx = 1; // Skip "pre-first-point" dummy intersection
  938. pointIndex = 0;
  939. unsigned int residual_top_points = intersection[1][TOP_EDGE].PointCount;
  940. unsigned int residual_bottom_points = intersection[1][BOTTOM_EDGE].PointCount;
  941. // Reduce both pointcounts by the same amount so the smaller one is 1 (skip points)
  942. unsigned int delta = MIN(residual_top_points, residual_bottom_points) - 1;
  943. residual_top_points -= delta;
  944. residual_bottom_points -= delta;
  945. pointIndex += delta;
  946. for (; ; )
  947. {
  948. if (residual_top_points == 1 && residual_bottom_points == 1)
  949. {
  950. // Advance both intersections, creating a tristrip segment
  951. v_index_array[triangleIndex].I = last_top_vertexIndex;
  952. v_index_array[triangleIndex].J = last_bottom_vertexIndex;
  953. v_index_array[triangleIndex].K = vertexIndex;
  954. triangleIndex++;
  955. v_index_array[triangleIndex].I = last_bottom_vertexIndex;
  956. v_index_array[triangleIndex].J = vertexIndex + 1;
  957. v_index_array[triangleIndex].K = vertexIndex;
  958. triangleIndex++;
  959. last_top_vertexIndex = vertexIndex;
  960. last_bottom_vertexIndex = vertexIndex + 1;
  961. // Advance both intersections.
  962. top_int_idx++;
  963. bottom_int_idx++;
  964. residual_top_points = intersection[top_int_idx][TOP_EDGE].PointCount;
  965. residual_bottom_points = intersection[bottom_int_idx][BOTTOM_EDGE].PointCount;
  966. // Advance point index (must do here because the new point index is used below):
  967. pointIndex++;
  968. // Generate two vertices for next point by picking nearest point on each direction line
  969. Vector3 &top_dir = intersection[top_int_idx][TOP_EDGE].Direction;
  970. top = top_dir * Vector3::Dot_Product(points[pointIndex], top_dir);
  971. Vector3 &bottom_dir = intersection[bottom_int_idx][BOTTOM_EDGE].Direction;
  972. bottom = bottom_dir * Vector3::Dot_Product(points[pointIndex], bottom_dir);
  973. vertexArray[vertexIndex].x = top.X;
  974. vertexArray[vertexIndex].y = top.Y;
  975. vertexArray[vertexIndex].z = top.Z;
  976. vertexArray[vertexIndex].u1 = u_values[0] ;
  977. vertexArray[vertexIndex].v1 = intersection[top_int_idx][TOP_EDGE].TexV ;
  978. vertexIndex++;
  979. vertexArray[vertexIndex].x = bottom.X;
  980. vertexArray[vertexIndex].y = bottom.Y;
  981. vertexArray[vertexIndex].z = bottom.Z;
  982. vertexArray[vertexIndex].u1 = u_values[1] ;
  983. vertexArray[vertexIndex].v1 = intersection[bottom_int_idx][BOTTOM_EDGE].TexV ;
  984. vertexIndex++;
  985. }
  986. else
  987. {
  988. // Exactly one of the pointcounts is greater than one - advance it and draw one triangle
  989. if (residual_top_points > 1)
  990. {
  991. // Draw one triangle (fan segment)
  992. v_index_array[triangleIndex].I = last_top_vertexIndex;
  993. v_index_array[triangleIndex].J = last_bottom_vertexIndex;
  994. v_index_array[triangleIndex].K = vertexIndex;
  995. triangleIndex++;
  996. last_bottom_vertexIndex = vertexIndex;
  997. // Advance bottom intersection only
  998. residual_top_points--;
  999. bottom_int_idx++;
  1000. residual_bottom_points = intersection[bottom_int_idx][BOTTOM_EDGE].PointCount;
  1001. // Advance point index (must do here because the new point index is used below):
  1002. pointIndex++;
  1003. // Generate bottom vertex by picking nearest point on bottom direction line
  1004. Vector3 &bottom_dir = intersection[bottom_int_idx][BOTTOM_EDGE].Direction;
  1005. bottom = bottom_dir * Vector3::Dot_Product(points[pointIndex], bottom_dir);
  1006. vertexArray[vertexIndex].x = bottom.X;
  1007. vertexArray[vertexIndex].y = bottom.Y;
  1008. vertexArray[vertexIndex].z = bottom.Z;
  1009. vertexArray[vertexIndex].u1 = u_values[1] ;
  1010. vertexArray[vertexIndex].v1 = intersection[bottom_int_idx][BOTTOM_EDGE].TexV ;
  1011. vertexIndex++;
  1012. }
  1013. else
  1014. {
  1015. // residual_bottom_points > 1
  1016. // Draw one triangle (fan segment)
  1017. v_index_array[triangleIndex].I = last_top_vertexIndex;
  1018. v_index_array[triangleIndex].J = last_bottom_vertexIndex;
  1019. v_index_array[triangleIndex].K = vertexIndex;
  1020. triangleIndex++;
  1021. last_top_vertexIndex = vertexIndex;
  1022. // Advance top intersection only
  1023. residual_bottom_points--;
  1024. top_int_idx++;
  1025. residual_top_points = intersection[top_int_idx][TOP_EDGE].PointCount;
  1026. // Advance point index (must do here because the new point index is used below):
  1027. pointIndex++;
  1028. // Generate top vertex by picking nearest point on top direction line
  1029. Vector3 &top_dir = intersection[top_int_idx][TOP_EDGE].Direction;
  1030. top = top_dir * Vector3::Dot_Product(points[pointIndex], top_dir);
  1031. vertexArray[vertexIndex].x = top.X;
  1032. vertexArray[vertexIndex].y = top.Y;
  1033. vertexArray[vertexIndex].z = top.Z;
  1034. vertexArray[vertexIndex].u1 = u_values[0] ;
  1035. vertexArray[vertexIndex].v1 = intersection[top_int_idx][TOP_EDGE].TexV ;
  1036. vertexIndex++;
  1037. }
  1038. }
  1039. // Reduce both pointcounts by the same amount so the smaller one is 1 (skip points)
  1040. delta = MIN(residual_top_points, residual_bottom_points) - 1;
  1041. residual_top_points -= delta;
  1042. residual_bottom_points -= delta;
  1043. pointIndex += delta;
  1044. // Exit conditions
  1045. if ( (top_int_idx >= num_intersections[TOP_EDGE] && residual_top_points == 1) ||
  1046. (bottom_int_idx >= num_intersections[BOTTOM_EDGE] && residual_bottom_points == 1))
  1047. {
  1048. // Debugging check - if either intersection index is before end, both of them should be
  1049. // and the points should be before the end.
  1050. assert(top_int_idx == num_intersections[TOP_EDGE]);
  1051. assert(bottom_int_idx == num_intersections[BOTTOM_EDGE]);
  1052. assert(pointIndex == point_cnt - 1);
  1053. break;
  1054. }
  1055. }
  1056. /*
  1057. ** Set color, opacity, vertex flags:
  1058. */
  1059. // If color is not white or opacity not 100%, enable gradient in shader and in renderer - otherwise disable.
  1060. //unsigned int rgba;
  1061. //rgba=DX8Wrapper::Convert_Color(Color,Opacity);
  1062. //bool rgba_all=(rgba==0xFFFFFFFF);
  1063. // int colorIndex = 0;
  1064. // for (vertexIndex = 0; vertexIndex < vnum; vertexIndex++)
  1065. // {
  1066. // //vertexArray[vertexIndex].diffuse = rgba;/// OLD WAY COLORS THEM ALL TO THE COLOR,OPACITY MEMBERS /////////////////
  1067. // unsigned int perPointARGB;
  1068. // colorIndex = MIN(vertexIndex / 2, point_cnt);
  1069. // perPointARGB = DX8Wrapper::Convert_Color( colors[colorIndex] );// twice as many verts as points? or so?
  1070. // vertexArray[vertexIndex].diffuse = perPointARGB;
  1071. // vertexArray[vertexIndex].u1 = (float)((vertexIndex&2) == 2);
  1072. // vertexArray[vertexIndex].v1 = (float)((vertexIndex&1) == 1);
  1073. // }
  1074. // Enable sorting if sorting has not been disabled and line is translucent and alpha testing is not enabled.
  1075. bool sorting = (!Is_Sorting_Disabled()) && (Shader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO && Shader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE);
  1076. ///////////////////////////////////////////////////////////////////////////////////////
  1077. ShaderClass shader = Shader;
  1078. shader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE);
  1079. shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE);
  1080. VertexMaterialClass *mat;
  1081. mat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE);
  1082. DX8Wrapper::Set_Material(mat);
  1083. REF_PTR_RELEASE(mat);
  1084. // If Texture is non-NULL enable texturing in shader - otherwise disable.
  1085. if (Texture)
  1086. {
  1087. shader.Set_Texturing(ShaderClass::TEXTURING_ENABLE);
  1088. }
  1089. else
  1090. {
  1091. shader.Set_Texturing(ShaderClass::TEXTURING_DISABLE);
  1092. }
  1093. ///////////////////////////////////////////////////////////////////////////////////////////
  1094. /*
  1095. ** Render
  1096. */
  1097. DynamicVBAccessClass Verts((sorting?BUFFER_TYPE_DYNAMIC_SORTING:BUFFER_TYPE_DYNAMIC_DX8),dynamic_fvf_type,vnum);
  1098. // Copy in the data to the VB
  1099. {
  1100. DynamicVBAccessClass::WriteLockClass Lock(&Verts);
  1101. unsigned int i;
  1102. unsigned char *vb=(unsigned char*)Lock.Get_Formatted_Vertex_Array();
  1103. const FVFInfoClass& fvfinfo=Verts.FVF_Info();
  1104. int segIdx = 0;
  1105. unsigned int argb = 0x00000000;
  1106. unsigned int oddEven = 0;
  1107. //oddEven = ( personalities[0] & 1 );
  1108. const unsigned verticesOffset = fvfinfo.Get_Location_Offset();
  1109. const unsigned diffuseOffset = fvfinfo.Get_Diffuse_Offset();
  1110. const unsigned textureOffset = fvfinfo.Get_Tex_Offset(0);
  1111. const unsigned vbSize = fvfinfo.Get_FVF_Size();
  1112. for (i=0; i<vnum; i++)
  1113. {
  1114. DEBUG_ASSERTCRASH(vertexArray[i].x != (float)0xdeadbeef && vertexArray[i].y != (float)0xdeadbeef && vertexArray[i].z != (float)0xdeadbeef && vertexArray[i].u1 != (float)0xdeadbeeef && vertexArray[i].v1 != (float)0xdeadbeef, ("Uninitialized vertexArray[%d]", i));
  1115. DEBUG_ASSERTCRASH((! _isnan(vertexArray[i].x) && _finite(vertexArray[i].x) && ! _isnan(vertexArray[i].y) && _finite(vertexArray[i].y) && ! _isnan(vertexArray[i].z) && _finite(vertexArray[i].z)) , ("Bad vertexArray[%d]", i));
  1116. Vector3 *vertex = reinterpret_cast<Vector3 *>(vb + verticesOffset);
  1117. vertex->X = vertexArray[i].x;
  1118. vertex->Y = vertexArray[i].y;
  1119. vertex->Z = vertexArray[i].z;
  1120. *reinterpret_cast<unsigned int *>(vb + diffuseOffset) = DX8Wrapper::Convert_Color_Clamp(colors[MIN((i/2), point_cnt)]); // TODO: Does not work correctly when subdivision are not 0
  1121. Vector2 *texture = reinterpret_cast<Vector2 *>(vb + textureOffset);
  1122. texture->U = vertexArray[i].u1;
  1123. texture->V = vertexArray[i].v1;
  1124. vb += vbSize;
  1125. }
  1126. } // copy
  1127. DynamicIBAccessClass ib_access((sorting?BUFFER_TYPE_DYNAMIC_SORTING:BUFFER_TYPE_DYNAMIC_DX8),triangleIndex*3);
  1128. {
  1129. unsigned int i;
  1130. DynamicIBAccessClass::WriteLockClass lock(&ib_access);
  1131. unsigned short* inds=lock.Get_Index_Array();
  1132. try {
  1133. for (i=0; i<triangleIndex; i++)
  1134. {
  1135. *inds++=v_index_array[i].I;
  1136. *inds++=v_index_array[i].J;
  1137. *inds++=v_index_array[i].K;
  1138. }
  1139. IndexBufferExceptionFunc();
  1140. } catch(...) {
  1141. IndexBufferExceptionFunc();
  1142. }
  1143. }
  1144. DX8Wrapper::Set_Index_Buffer(ib_access,0);
  1145. DX8Wrapper::Set_Vertex_Buffer(Verts);
  1146. DX8Wrapper::Set_Texture(0,Texture);
  1147. DX8Wrapper::Set_Shader(shader);
  1148. if (sorting)
  1149. {
  1150. SortingRendererClass::Insert_Triangles(obj_sphere,0,triangleIndex,0,vnum);
  1151. }
  1152. else
  1153. {
  1154. DX8Wrapper::Draw_Triangles(0,triangleIndex,0,vnum);
  1155. }
  1156. } // Chunking loop
  1157. DX8Wrapper::Set_Transform(D3DTS_VIEW,view);
  1158. }
  1159. /////////////////////////////////////////////////////////////////////////////
  1160. /////////////////////////////////////////////////////////////////////////////
  1161. /////////////////////////////////////////////////////////////////////////////
  1162. /////////////////////////////////////////////////////////////////////////////
  1163. /////////////////////////////////////////////////////////////////////////////
  1164. VertexFormatXYZUV1 *StreakRendererClass::getVertexBuffer(unsigned int number)
  1165. {
  1166. // TODO: use a stl vector instead of our own array.
  1167. if (number > m_vertexBufferSize)
  1168. {
  1169. unsigned int numberToAlloc = number + (number >> 1);
  1170. delete [] m_vertexBuffer;
  1171. m_vertexBuffer = W3DNEWARRAY VertexFormatXYZUV1[numberToAlloc];
  1172. m_vertexBufferSize = numberToAlloc;
  1173. }
  1174. #ifdef _INTERNAL
  1175. for (unsigned i = 0; i < number; ++i)
  1176. {
  1177. m_vertexBuffer[i].x = m_vertexBuffer[i].y = m_vertexBuffer[i].z = m_vertexBuffer[i].u1 = m_vertexBuffer[i].v1 = (float)0xdeadbeef;
  1178. }
  1179. #endif
  1180. return m_vertexBuffer;
  1181. }