seglinerenderer.cpp 51 KB

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