intersec.inl 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. /*
  2. ** Command & Conquer Renegade(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. #if defined(_MSC_VER)
  19. #pragma once
  20. #endif
  21. #ifndef INTERSEC_INL
  22. #define INTERSEC_INL
  23. #include "camera.h"
  24. /// debug code that will be tossed
  25. #ifdef DEBUG_NORMALS
  26. #include "d:/g/app/main/debug_o.h"
  27. inline bool Verify_Normal(Vector3 &Normal, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3)
  28. {
  29. double d1 = Vector3::Dot_Product(Normal, loc1);
  30. double d2 = Vector3::Dot_Product(Normal, loc2);
  31. double d3 = Vector3::Dot_Product(Normal, loc3);
  32. double e1 = d1 - d2;
  33. double e2 = d2 - d3;
  34. double e3 = d3 - d1;
  35. if((fabs(e1) > 0.001) || (fabs(e2) > 0.001) || (fabs(e3) > 0.001)) {
  36. Debug.Print("----------\n");
  37. Debug.Print("dots", Vector3(d1,d2,d3));
  38. Debug.Print("err", Vector3(e1,e2,e3));
  39. return false;
  40. }
  41. return true;
  42. }
  43. inline void Verify_Normal2(Vector3 &Normal, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3)
  44. {
  45. Vector3 v1 = loc2 - loc1;
  46. Vector3 v2 = loc3 - loc1;
  47. Vector3 normal = Vector3::Cross_Product(v1,v2);
  48. normal.Normalize();
  49. if(!Verify_Normal(Normal, loc1,loc2,loc3)) {
  50. Vector3 diff = Normal - normal;
  51. if(Verify_Normal(normal, loc1,loc2,loc3)) {
  52. Debug.Print("calculated worked.\n");
  53. }
  54. }
  55. // Normal = normal;
  56. }
  57. #endif
  58. //// end of debug code to toss
  59. /*
  60. ** Determine the ray that corresponds to the specified screen coordinates with respect
  61. ** to the camera location, direction and projection information.
  62. */
  63. inline void IntersectionClass::Get_Screen_Ray(float screen_x, float screen_y, const LayerClass &Layer)
  64. {
  65. // copy screen coords to member data
  66. ScreenX = screen_x;
  67. ScreenY = screen_y;
  68. // extract needed pointers from the world
  69. CameraClass *camera = Layer.Camera;
  70. // determine the ray corresponding to the camera and distance to projection plane
  71. Matrix3D camera_matrix = camera->Get_Transform();
  72. Vector3 camera_location = camera->Get_Position();
  73. // the projected ray has the same origin as the camera
  74. *RayLocation = camera_location;
  75. // these 6 lines worked for SR 1.1
  76. // build the projected screen vector
  77. // float x_offset = width / (float)Scene->width; // render width in pixels divided by display width in pixels = ratio of displayed area
  78. // float y_offset = height / (float)Scene->height;
  79. // float zmod = Scene->perspective;
  80. // float xmod = ((ScreenX / x_offset) * width - xmid - Scene->xstart) * zmod * 16384.0f/ (Scene->axratio * 128.0f);
  81. // float ymod = ((ScreenY / y_offset) * height - ymid - Scene->ystart) * zmod * 16384.0f/ (Scene->ayratio * 128.0f);
  82. // determine the location of the screen coordinate in camera-model space
  83. const ViewportClass &viewport = camera->Get_Viewport();
  84. // float aspect = camera->Get_Aspect_Ratio();
  85. Vector2 min,max;
  86. camera->Get_View_Plane(min,max);
  87. float xscale = (max.X - min.X);
  88. float yscale = (max.Y - min.Y);
  89. float zmod = -1.0; // Scene->vpd; // Note: view plane distance is now always 1.0 from the camera
  90. float xmod = (-ScreenX + 0.5 + viewport.Min.X) * zmod * xscale;// / aspect;
  91. float ymod = (ScreenY - 0.5 - viewport.Min.Y) * zmod * yscale;// * aspect;
  92. // float xmod = (ScreenX - 0.5 - viewport.Min.X) * zmod / Scene->axratio;
  93. // float ymod = (ScreenY - 0.5 - viewport.Min.Y) * zmod / Scene->ayratio;
  94. // sr1.2
  95. // float xmod = (ScreenX - 0.5 - Scene->xstart) * zmod / Scene->axratio;
  96. // float ymod = (ScreenY - 0.5 - Scene->ystart) * zmod / Scene->ayratio;
  97. // sr1.1
  98. // float xmod = x_offset * zmod; //projection_width;
  99. // float ymod = y_offset * zmod; //projection_height;
  100. // transform the screen coordinates by the camera's matrix into world coordinates.
  101. float x = zmod * camera_matrix[0][2] + xmod * camera_matrix[0][0] + ymod * camera_matrix[0][1];
  102. float y = zmod * camera_matrix[1][2] + xmod * camera_matrix[1][0] + ymod * camera_matrix[1][1];
  103. float z = zmod * camera_matrix[2][2] + xmod * camera_matrix[2][0] + ymod * camera_matrix[2][1];
  104. RayDirection->Set(x,y,z);
  105. RayDirection->Normalize();
  106. // set the maximum intersection distance to the back clipping plane
  107. MaxDistance = camera->Get_Depth();
  108. //Max_Distance = Scene->zstop * Scene->depth;
  109. }
  110. /*
  111. ** This is the Point_In_Polygon_Z low level function, optimized for use by _Intersect_Triangles_Z.
  112. ** If it is inside, it will adjust the Z value of the point to be on the triangle plane.
  113. */
  114. inline bool IntersectionClass::_Point_In_Polygon_Z(
  115. Vector3 &Point,
  116. Vector3 &Corner1,
  117. Vector3 &Corner2,
  118. Vector3 &Corner3
  119. )
  120. {
  121. // these defines could be variables if support for other axis were neccessary
  122. #define AXIS_1 0
  123. #define AXIS_2 1
  124. #define AXIS_3 2
  125. double u0 = Point[AXIS_1] - Corner1[AXIS_1];
  126. double v0 = Point[AXIS_2] - Corner1[AXIS_2];
  127. // determine the 2d vectors on the dominant plane from the first vertex to the other two
  128. double u1 = Corner2[AXIS_1] - Corner1[AXIS_1];
  129. double v1 = Corner2[AXIS_2] - Corner1[AXIS_2];
  130. double u2 = Corner3[AXIS_1] - Corner1[AXIS_1];
  131. double v2 = Corner3[AXIS_2] - Corner1[AXIS_2];
  132. double alpha, beta;
  133. bool intersect = false;
  134. // calculate alpha and beta as normalized (0..1) percentages across the 2d projected triangle
  135. // and do bounds checking (sum <= 1) to determine whether or not the triangle intersection occurs.
  136. if (u1 == 0.0f) {
  137. beta = u0 / u2; // beta is the percentage down the edge Corner1->Corner3
  138. if ((beta >= 0.0f) && (beta <= 1.0f)) { // make sure it's within the edge segment
  139. alpha = (v0 - beta * v2) / v1; // alpha is the percentage down the edge Corner1->Corner2
  140. // if alpha is valid & the sum of alpha & beta is <= 1 then it's within the triangle
  141. // note: 0.00001 added after testing an intersection of a square in the middle indicated
  142. // an error of 0.0000001350, apparently due to roundoff.
  143. intersect = ((alpha >= 0.0) && ((alpha + beta) <= 1.0));
  144. }
  145. } else {
  146. beta = (v0 * u1 - u0 * v1) / (v2 * u1 - u2 * v1);
  147. if ((beta >= 0.0) && (beta <= 1.0)) {
  148. alpha = (u0 - beta * u2) / u1;
  149. intersect = ((alpha >= 0.0) && ((alpha + beta) <= 1.0));
  150. }
  151. }
  152. // if it is inside, adjust the Z value to sit upon the triangle plane.
  153. if(intersect) {
  154. float u3 = Corner2[AXIS_3] - Corner1[AXIS_3];
  155. float v3 = Corner3[AXIS_3] - Corner1[AXIS_3];
  156. Point[AXIS_3] = u3 * alpha + v3 * beta + Corner1[AXIS_3];
  157. }
  158. return intersect;
  159. }
  160. /*
  161. ** Another way to access the Point_In_Polygon function
  162. **
  163. */
  164. inline bool IntersectionClass::_Point_In_Polygon_Z(
  165. Vector3 &Point,
  166. Vector3 Corners[3]
  167. )
  168. {
  169. return _Point_In_Polygon_Z(Point, Corners[0], Corners[1], Corners[2]);
  170. }
  171. /*
  172. ** This is the general purpose Point_In_Polygon low level function. It can be called directly if you know
  173. ** the dominant projection axes, such as in the case of 2d intersecion with heightfields.
  174. */
  175. inline bool IntersectionClass::_Point_In_Polygon(
  176. Vector3 &Point,
  177. Vector3 &loc1,
  178. Vector3 &loc2,
  179. Vector3 &loc3,
  180. int axis_1,
  181. int axis_2,
  182. float &Alpha,
  183. float &Beta)
  184. {
  185. double u0 = Point[axis_1] - loc1[axis_1];
  186. double v0 = Point[axis_2] - loc1[axis_2];
  187. // determine the 2d vectors on the dominant plane from the first vertex to the other two
  188. double u1 = loc2[axis_1] - loc1[axis_1];
  189. double v1 = loc2[axis_2] - loc1[axis_2];
  190. double u2 = loc3[axis_1] - loc1[axis_1];
  191. double v2 = loc3[axis_2] - loc1[axis_2];
  192. double alpha, beta;
  193. bool intersect = false;
  194. // calculate alpha and beta as normalized (0..1) percentages across the 2d projected triangle
  195. // and do bounds checking (sum <= 1) to determine whether or not the triangle intersection occurs.
  196. #ifdef DEBUG_NORMALS
  197. bool debugmode = false;
  198. if(FinalResult->Alpha == 777) {
  199. debugmode = true;
  200. }
  201. #endif
  202. if (u1 == 0.0f) {
  203. Beta = beta = u0 / u2; // beta is the percentage down the edge loc1->loc3
  204. if ((beta >= 0.0f) && (beta <= 1.0f)) { // make sure it's within the edge segment
  205. Alpha = alpha = (v0 - beta * v2) / v1; // alpha is the percentage down the edge loc1->loc2
  206. // if alpha is valid & the sum of alpha & beta is <= 1 then it's within the triangle
  207. // note: 0.00001 added after testing an intersection of a square in the middle indicated
  208. // an error of 0.0000001350, apparently due to roundoff.
  209. intersect = ((alpha >= 0.0) && ((alpha + beta) <= 1.0));
  210. }
  211. } else {
  212. Beta = beta = (v0 * u1 - u0 * v1) / (v2 * u1 - u2 * v1);
  213. if ((beta >= 0.0) && (beta <= 1.0)) {
  214. Alpha = alpha = (u0 - beta * u2) / u1;
  215. intersect = ((alpha >= 0.0) && ((alpha + beta) <= 1.0));
  216. }
  217. }
  218. #ifdef DEBUG_NORMALS
  219. if(debugmode) {
  220. Debug.Print("Intersect", intersect);
  221. Debug.Print("Normal ", Normal);
  222. Debug.Print("Point 1", loc1);
  223. Debug.Print("Point 2", loc2);
  224. Debug.Print("Point 3", loc3);
  225. Debug.Print("Inter ", FinalResult->Intersection);
  226. Debug.Print("a/b", (float) alpha, (float) beta);
  227. Debug.Print("sum", (float) alpha + (float) beta);
  228. Debug.Print("diff", (float) (alpha - beta));
  229. float d1 = Vector3::Dot_Product(Normal, loc1);
  230. float d2 = Vector3::Dot_Product(Normal, loc2);
  231. float d3 = Vector3::Dot_Product(Normal, loc3);
  232. float e1 = d1 - d2;
  233. float e2 = d2 - d3;
  234. float e3 = d3 - d1;
  235. Debug.Print("dots", Vector3(d1,d2,d3));
  236. Debug.Print("err", Vector3(e1,e2,e3));
  237. }
  238. #endif
  239. return intersect;
  240. }
  241. /*
  242. ** This version calls the base form using member data from the FinalResult struct for
  243. ** some of it's arguments.
  244. */
  245. inline bool IntersectionClass::_Point_In_Polygon(
  246. IntersectionResultClass *FinalResult,
  247. Vector3 &loc1,
  248. Vector3 &loc2,
  249. Vector3 &loc3,
  250. int axis_1,
  251. int axis_2)
  252. {
  253. return (FinalResult->Intersects = _Point_In_Polygon( FinalResult->Intersection, loc1, loc2, loc3,
  254. axis_1, axis_2, FinalResult->Alpha, FinalResult->Beta));
  255. }
  256. /*
  257. ** This version determines the dominant plane of the 3d triangle to be point-in-poly tested
  258. ** and then calls the next form of _Point_In_Polygon
  259. */
  260. inline bool IntersectionClass::_Point_In_Polygon(IntersectionResultClass *FinalResult, Vector3 &Normal, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3) {
  261. // first, find the dominant axis and use the plane perpendicular to it as defined by axis_1, axis_2
  262. int axis_1, axis_2;
  263. _Find_Polygon_Dominant_Plane(Normal, axis_1, axis_2);
  264. return _Point_In_Polygon(FinalResult, loc1, loc2, loc3, axis_1, axis_2);
  265. }
  266. /*
  267. ** Determine the Z distance to the specified polygon.
  268. */
  269. inline float IntersectionClass::Plane_Z_Distance(Vector3 &PlaneNormal, Vector3 &PlanePoint)
  270. {
  271. // do a parallel check
  272. float divisor = (PlaneNormal[0] *(*RayDirection)[0] + PlaneNormal[1] *(*RayDirection)[1] + PlaneNormal[2] * (*RayDirection)[2]);
  273. if(divisor == 0) return false; // parallel
  274. // determine distance to plane
  275. double d = - (PlanePoint[0] * PlaneNormal[0] + PlanePoint[1] * PlaneNormal[1] + PlanePoint[2] * PlaneNormal[2]);
  276. float value = - (d + PlaneNormal[0] * (*RayLocation)[0] + PlaneNormal[1] * (*RayLocation)[1] + PlaneNormal[2] * (*RayLocation)[2]) / divisor;
  277. return value;
  278. }
  279. /*
  280. ** This function will find the z elevation for the passed Vector3 whose x/y components
  281. ** are defined, using the specified vertex & surface normal to determine the correct value
  282. */
  283. inline float IntersectionClass::_Get_Z_Elevation(
  284. Vector3 &Point,
  285. Vector3 &PlanePoint,
  286. Vector3 &PlaneNormal)
  287. {
  288. // do a parallel check
  289. if(PlaneNormal[2] == 0) return false;
  290. // determine distance to plane
  291. double d = - (PlanePoint[0] * PlaneNormal[0] + PlanePoint[1] * PlaneNormal[1] + PlanePoint[2] * PlaneNormal[2]);
  292. float value = - (d + PlaneNormal[0] * Point[0] + PlaneNormal[1] * Point[1] ) / PlaneNormal[2];
  293. return value;
  294. }
  295. /*
  296. ** Optimized intersection test that only considers the x/y component of the intersection object
  297. ** and will determine the intersection location down the Z axis.
  298. */
  299. inline bool IntersectionClass::Intersect_Polygon_Z(IntersectionResultClass *Result, Vector3 &PolygonNormal, Vector3 &v1, Vector3 &v2, Vector3 &v3)
  300. {
  301. Result->Range = Plane_Z_Distance(PolygonNormal, v1);
  302. (Result->Intersection)[0] = (*RayLocation)[0];
  303. (Result->Intersection)[1] = (*RayLocation)[1];
  304. (Result->Intersection)[2] = (*RayLocation)[2] - Result->Range;
  305. return _Point_In_Polygon(Result, PolygonNormal, v1, v2, v3);
  306. }
  307. /*
  308. ** Scale the normalized direction ray to the distance of intersection
  309. */
  310. void IntersectionClass::Calculate_Intersection(IntersectionResultClass *Result)
  311. {
  312. (Result->Intersection)[0] = (*RayLocation)[0] + (*RayDirection)[0] * Result->Range;
  313. (Result->Intersection)[1] = (*RayLocation)[1] + (*RayDirection)[1] * Result->Range;
  314. (Result->Intersection)[2] = (*RayLocation)[2] + (*RayDirection)[2] * Result->Range;
  315. }
  316. /*
  317. ** Plane intersection test that assumes a normalized RayDirection. Only determines if
  318. ** plane is parallel and if not, the range to it (which may be negative or beyond MaxRange).
  319. ** It doesn't determine point of intersection either.
  320. */
  321. inline bool IntersectionClass::Intersect_Plane_Quick(IntersectionResultClass *Result, Vector3 &PlaneNormal, Vector3 &PlanePoint)
  322. {
  323. // do a parallel check
  324. float divisor = (PlaneNormal[0] *(*RayDirection)[0] + PlaneNormal[1] *(*RayDirection)[1] + PlaneNormal[2] * (*RayDirection)[2]);
  325. if(divisor == 0) return false; // parallel
  326. // determine distance to plane
  327. float d = - (PlanePoint[0] * PlaneNormal[0] + PlanePoint[1] * PlaneNormal[1] + PlanePoint[2] * PlaneNormal[2]);
  328. Result->Range = - (d + PlaneNormal[0] * (*RayLocation)[0] + PlaneNormal[1] * (*RayLocation)[1] + PlaneNormal[2] * (*RayLocation)[2]) / divisor;
  329. return true;
  330. }
  331. /*
  332. ** Determine if the specified ray will intersect the plane; returns false for planes
  333. ** parallel and behind ray origin.
  334. ** Sets Range to the distance from the ray location to the intersection.
  335. ** Note: Range is undefined if an intersection didn't occur.
  336. */
  337. inline bool IntersectionClass::Intersect_Plane(IntersectionResultClass *Result, Vector3 &PlaneNormal, Vector3 &PlanePoint) {
  338. // normalize the ray direction
  339. RayDirection->Normalize();
  340. // call the quick test routine
  341. if(!Intersect_Plane_Quick(Result, PlaneNormal, PlanePoint)) return false;
  342. // check to make sure it's not behind the ray's origin
  343. if(Result->Range <= 0) return false;
  344. // check to make sure it's not beyond max distance
  345. if(Result->Range > MaxDistance) return false;
  346. // determine point of intersection
  347. Calculate_Intersection(Result);
  348. return true;
  349. }
  350. /*
  351. ** Return the index of the largest normal component 0..2
  352. ** used by Find_Triangle_Dominant_Plane()
  353. */
  354. inline int IntersectionClass::_Largest_Normal_Index(Vector3 &v)
  355. {
  356. float x = fabsf(v[0]);
  357. float y = fabsf(v[1]);
  358. float z = fabsf(v[2]);
  359. if(x > y) {
  360. if(x > z) {
  361. return 0; // x > y && x > z --> x is the max
  362. }
  363. return 2; // x > y && !(x > z) --> z is the max
  364. }
  365. if(y > z)
  366. return 1; // x <= y && y > z --> y is the max
  367. return 2; // y > x && y > z --> z is the max
  368. }
  369. /*
  370. ** Use the Polygon's currently defined surface normal to determine it's dominant axis.
  371. ** Axis_1 and Axis_2 are set to the indices of the two axis that define the dominant plane.
  372. */
  373. inline void IntersectionClass::_Find_Polygon_Dominant_Plane(Vector3 &Normal, int &Axis_1, int &Axis_2)
  374. {
  375. switch (_Largest_Normal_Index(Normal))
  376. {
  377. case 0:
  378. // Dominant is the X axis
  379. Axis_1 = 2;
  380. Axis_2 = 1;
  381. break;
  382. case 1:
  383. // Dominant is the Y axis
  384. Axis_1 = 2;
  385. Axis_2 = 0;
  386. break;
  387. case 2:
  388. // Dominant is the Z axis
  389. Axis_1 = 0;
  390. Axis_2 = 1;
  391. break;
  392. }
  393. }
  394. /*
  395. ** Returns true if ray intersects polygon.
  396. ** Changes passed Intersection argument to location of intersection if it occurs,
  397. ** and sets Range to the distance from the ray location to the intersection.
  398. ** If Interpolated_Normal is specified it will interpolate the surface normal based
  399. ** on the vertex normals.
  400. */
  401. inline bool IntersectionClass::Intersect_Polygon(IntersectionResultClass *Result, Vector3 &PolygonNormal, Vector3 &v1, Vector3 &v2, Vector3 &v3)
  402. {
  403. // first check to see if it hits the plane; determine plane normal and find point on plane (from a vertex)
  404. #ifdef DEBUG_NORMALS
  405. Verify_Normal2(PolygonNormal, v1,v2,v3);
  406. #endif
  407. if(Intersect_Plane(Result, PolygonNormal, v1)) {
  408. // then check to see if it it actually intersects the polygon.
  409. return _Point_In_Polygon(Result, PolygonNormal, v1, v2, v3);
  410. }
  411. // doesn't even hit the plane, return false.
  412. return false;
  413. }
  414. /*
  415. ** This version will calc the normal for the polygon before calling
  416. ** a lower form of Intersect_Polygon
  417. */
  418. inline bool IntersectionClass::Intersect_Polygon(IntersectionResultClass *Result, Vector3 &v1, Vector3 &v2, Vector3 &v3)
  419. {
  420. Vector3 vec1 = v2 - v1;
  421. Vector3 vec2 = v3 - v1;
  422. Vector3 normal = Vector3::Cross_Product(vec1, vec2);
  423. return Intersect_Polygon(Result, normal, v1,v2,v3);
  424. }
  425. // called after Interpolate_Intersection_Normal.
  426. // transform the intersection and the normal from model coords into world coords
  427. inline void IntersectionClass::Transform_Model_To_World_Coords(IntersectionResultClass *FinalResult) {
  428. FinalResult->Intersection = FinalResult->ModelMatrix * FinalResult->Intersection + FinalResult->ModelLocation;
  429. if(IntersectionNormal != 0) {
  430. Vector3 normal(*IntersectionNormal);
  431. *IntersectionNormal = FinalResult->ModelMatrix * normal;
  432. }
  433. }
  434. bool IntersectionClass::Intersect_Screen_Object( IntersectionResultClass *Final_Result,
  435. Vector4 &Area,
  436. RenderObjClass *obj)
  437. {
  438. if(Final_Result->Intersects = ((ScreenX >= Area[0]) && (ScreenX <= Area[2]) && (ScreenY >= Area[1]) && (ScreenY <= Area[3]))) {
  439. Final_Result->IntersectionType = IntersectionResultClass::GENERIC;
  440. Final_Result->IntersectedRenderObject = obj;
  441. Final_Result->Range = 0;
  442. return true;
  443. }
  444. return false;
  445. }
  446. /*
  447. ** Determines the point of intersection, if any between the line segments AB and CD.
  448. ** If an intersection occurs, then the UV values are interpolated along AB.
  449. ** Disregards the Z value and considers only the X/Y data except for determining
  450. ** the Z value of the intersection.
  451. ** This function could be easily modified to support other axes.
  452. * /
  453. void IntersectionClass::_Intersect_Lines_Z(
  454. Vector3 &A,
  455. Vector3 &B,
  456. Vector2 &UVStart,
  457. Vector2 &UVEnd,
  458. Vector3 &C,
  459. Vector3 &D,
  460. Vector3 ClippedPoints[6],
  461. Vector2 ClippedUV[6],
  462. int &DestIndex)
  463. {
  464. /*
  465. Let A,B,C,D be 2-space position vectors. Then the directed line segments AB & CD are given by:
  466. AB=A+r(B-A), r in [0,1]
  467. CD=C+s(D-C), s in [0,1]
  468. If AB & CD intersect, then
  469. A+r(B-A)=C+s(D-C), or
  470. Ax+r(Bx-Ax)=Cx+s(Dx-Cx)
  471. Ay+r(By-Ay)=Cy+s(Dy-Cy) for some r,s in [0,1]
  472. Solving the above for r and s yields
  473. (Ay-Cy)(Dx-Cx)-(Ax-Cx)(Dy-Cy)
  474. r = ----------------------------- (eqn 1)
  475. (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx)
  476. (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay)
  477. s = ----------------------------- (eqn 2)
  478. (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx)
  479. Let P be the position vector of the intersection point, then
  480. P=A+r(B-A) or
  481. Px=Ax+r(Bx-Ax)
  482. Py=Ay+r(By-Ay)
  483. By examining the values of r & s, you can also determine some other limiting conditions:
  484. If 0<=r<=1 & 0<=s<=1, intersection exists
  485. r<0 or r>1 or s<0 or s>1 line segments do not intersect
  486. If the denominator in eqn 1 is zero, AB & CD are parallel
  487. If the numerator in eqn 1 is also zero, AB & CD are coincident
  488. If the intersection point of the 2 lines are needed (lines in this context mean infinite lines) regardless whether the two line segments intersect, then
  489. If r>1, P is located on extension of AB
  490. If r<0, P is located on extension of BA
  491. If s>1, P is located on extension of CD
  492. If s<0, P is located on extension of DC
  493. * /
  494. // the numerator is required for all execution routes
  495. float numerator = (A[AXIS_2] - C[AXIS_2]) * (D[AXIS_1] - C[AXIS_1]) - (A[AXIS_1] - C[AXIS_1]) * (D[AXIS_2] - C[AXIS_2]);
  496. // if the denominator is zero, then the segments are parallel.
  497. float denominator = (B[AXIS_1] - A[AXIS_1]) * (D[AXIS_2] - C[AXIS_2]) - (B[AXIS_2] - A[AXIS_2]) * (D[AXIS_1] - C[AXIS_1]);
  498. // r & s are percentages through the line segment.
  499. float r, s;
  500. // check to see if they are parallel
  501. if(denominator == 0) {
  502. // check to see if they are coincident
  503. // a numerator of zero with a denominator of zero indicates coincident lines.
  504. if (numerator != 0) {
  505. // parallel, not coincident lines (and segments) do not intersect.
  506. return;
  507. }
  508. // perform special case for parallel segments
  509. // determine relative position 0..1 of C and D on one of the 1d vectors of A-B
  510. float len = B[AXIS_1] - A[AXIS_1];
  511. float cpos,dpos;
  512. // if the length of the edge on the first axis is zero, use the other axis instead.
  513. if(len) {
  514. len = 1.0 / len;
  515. cpos = (C[AXIS_1] - A[AXIS_1]) * len;
  516. dpos = (D[AXIS_1] - A[AXIS_1]) * len;
  517. } else {
  518. len = B[AXIS_2] - A[AXIS_2];
  519. // degenerate triangle test
  520. if(len == 0)
  521. return;
  522. len = 1.0 / len;
  523. cpos = (C[AXIS_2] - A[AXIS_2]) * len;
  524. dpos = (D[AXIS_2] - A[AXIS_2]) * len;
  525. }
  526. // check to see if there's any overlap
  527. // one of the two pos values must be 0>pos>1 or there is no intersection.
  528. // this test will ensure that cpos & dpos will not both be outside the same end of the segment.
  529. if(((cpos < 0) && (dpos < 0)) || ((cpos > 1) && (dpos > 1)))
  530. return;
  531. if(cpos < 0) {
  532. // C is outside, therefore D is inside or on other side.
  533. // use the original vertex.
  534. ClippedPoints[DestIndex] = A;
  535. ClippedUV[DestIndex++] = UVStart;
  536. } else if (cpos > 1) {
  537. // C is outside far side, therefore D is inside or on other side.
  538. // use the far vertex.
  539. ClippedPoints[DestIndex] = B;
  540. ClippedUV[DestIndex++] = UVEnd;
  541. } else {
  542. // C is inside.
  543. // Use C as the vertex, and interpolate the UV coords.
  544. ClippedPoints[DestIndex] = C;
  545. ClippedUV[DestIndex++] = (UVEnd - UVStart) * cpos + UVStart;
  546. }
  547. if(dpos < 0) {
  548. // D is outside near vertex, therefore C is inside or outside far vertex
  549. // use near vertex
  550. ClippedPoints[DestIndex] = A;
  551. ClippedUV[DestIndex++] = UVStart;
  552. } else if (dpos > 1) {
  553. // D is outside far vertex, therefore C is inside or outside the near vertex.
  554. // use the far vertex.
  555. ClippedPoints[DestIndex] = B;
  556. ClippedUV[DestIndex++] = UVEnd;
  557. } else {
  558. // D is inside.
  559. // Use D as the vertex, and interpolate the UV coords.
  560. ClippedPoints[DestIndex] = D;
  561. ClippedUV[DestIndex++] = (UVEnd - UVStart) * dpos + UVStart;
  562. }
  563. return;
  564. }
  565. // determine the percentage into the line segments that the intersection occurs.
  566. // an intersection of segments will produce r & s values between 0 & 1.
  567. denominator = 1.0 / denominator;
  568. r = numerator * denominator;
  569. numerator = (A[AXIS_2] - C[AXIS_2]) * (B[AXIS_1] - A[AXIS_1]) - (A[AXIS_1] - C[AXIS_1]) * (B[AXIS_2] - A[AXIS_2]);
  570. s = numerator * denominator;
  571. // determine if the line intersect within the defined segments.
  572. if((0.0 <= r) && (r <= 1.0) && (0.0 <= s) && (s <= 1.0)) {
  573. // they intersect.
  574. // determine intersection point
  575. Vector3 v = D - C;
  576. // float len = v.Length();
  577. ClippedPoints[DestIndex] = C + v * s;
  578. // interpolate UV values
  579. Vector2 uv = UVEnd - UVStart;
  580. // len = uv.Length();
  581. ClippedUV[DestIndex++] = UVStart + uv * r;
  582. }
  583. }
  584. /*
  585. A failed attempt to use a graphics gem vol 2 example
  586. // Compute a1, b1, c1, where line joining points 1 and 2
  587. // is "a1 x + b1 y + c1 = 0".
  588. float a1 = B[AXIS_2] - A[AXIS_2];
  589. float b1 = B[AXIS_1] - A[AXIS_1];
  590. float c1 = B[AXIS_2] * A[AXIS_1] - A[AXIS_1] * B[AXIS_2];
  591. // Compute r3 & r4, the sign values
  592. float r3 = a1 * C[AXIS_1] + b1 * C[AXIS_2] + c1;
  593. float r4 = a1 * D[AXIS_1] + b1 * D[AXIS_2] + c1;
  594. // Check signs of r3 and r4. If both point 3 and point 4 lie on
  595. // same side of line 1, the line segments do not intersect.
  596. if ( r3 != 0 && r4 != 0 && (((r3 < 0) && (r4 < 0)) || ((r3 > 0) && (r4 > 0)))
  597. return; // ( DONT_INTERSECT );
  598. // Compute a2, b2, c2
  599. float a2 = D[AXIS_2] - C[AXIS_2];
  600. float b2 = C[AXIS_1] - D[AXIS_1];
  601. float c2 = D[AXIS_1] * C[AXIS_2] - C[AXIS_1] * D[AXIS_2];
  602. // Compute r1 and r2
  603. float r1 = a2 * A[AXIS_1] + b2 * A[AXIS_2] + c2;
  604. float r2 = a2 * B[AXIS_1] + b2 * B[AXIS_2] + c2;
  605. // Check signs of r1 and r2. If both point 1 and point 2 lie
  606. // on same side of second line segment, the line segments do
  607. // not intersect.
  608. if ( r1 != 0 && r2 != 0 && (((r1 < 0) && (r2 < 0)) || ((r1 > 0) && (r2 > 0))))
  609. return; // ( DONT_INTERSECT );
  610. // Line segments intersect: compute intersection point.
  611. float denom = a1 * b2 - a2 * b1;
  612. if ( denom == 0 )
  613. return; // ( COLLINEAR );
  614. float offset = denom < 0 ? - denom * 0.5f : denom * 0.5f;
  615. // The denom/2 is to get rounding instead of truncating. It
  616. // is added or subtracted to the numerator, depending upon the
  617. // sign of the numerator.
  618. float num = b1 * c2 - b2 * c1;
  619. float x = ( num < 0 ? num - offset : num + offset ) / denom;
  620. num = a2 * c1 - a1 * c2;
  621. float y = ( num < 0 ? num - offset : num + offset ) / denom;
  622. ClippedPoints[DestIndex] = Vector3(x,y,0);
  623. ClippedUV[DestIndex++] = Vector3
  624. return; //( DO_INTERSECT ); // lines_intersect
  625. */
  626. inline bool IntersectionClass::In_Front_Of_Line
  627. (
  628. const Vector3 & p, // point to test
  629. const Vector3 & e0, // point on edge
  630. const Vector3 & de // direction of edge
  631. )
  632. {
  633. Vector3 dp = p - e0;
  634. float val = de.X*dp.Y - de.Y*dp.X;
  635. if (val > 0.0f) {
  636. return true;
  637. }
  638. return false;
  639. }
  640. inline float IntersectionClass::Intersect_Lines
  641. (
  642. const Vector3 & p0, // start of line segment
  643. const Vector3 & p1, // end of line segment
  644. const Vector3 & e0, // point on clipping edge
  645. const Vector3 & de // direction of clipping edge
  646. )
  647. {
  648. float dpx = p1.X - p0.X;
  649. float dpy = p1.Y - p0.Y;
  650. float den = de.Y * dpx - de.X * dpy;
  651. if (fabs(den) > WWMATH_EPSILON) {
  652. float num = p0.Y*de.X - p0.X*de.Y + e0.X*de.Y - e0.Y*de.X;
  653. float t = num/den;
  654. if ((t >= 0.0f) && (t <= 1.0f)) {
  655. return t;
  656. }
  657. }
  658. return 0.0f;
  659. }
  660. #define EMIT(p,uv) OutPoints[outnum] = p; OutUVs[outnum] = uv; outnum++;
  661. inline int IntersectionClass::Clip_Triangle_To_LineXY(
  662. int incount,
  663. Vector3 * InPoints,
  664. Vector2 * InUVs,
  665. Vector3 * OutPoints,
  666. Vector2 * OutUVs,
  667. const Vector3 & edge_point0,
  668. const Vector3 & edge_point1
  669. )
  670. {
  671. Vector3 e0 = edge_point0;
  672. Vector3 de = edge_point1 - edge_point0;
  673. // number of verts output.
  674. int outnum = 0;
  675. // start and end verts of the current edge
  676. int p0,p1;
  677. p0 = incount-1;
  678. // intersection temporaries.
  679. float intersection;
  680. Vector3 intersection_point;
  681. Vector2 intersection_uv;
  682. // loop over each edge in the input polygon
  683. for (p1=0; p1<incount; p1++) {
  684. if (In_Front_Of_Line(InPoints[p1],e0,de)) {
  685. if (In_Front_Of_Line(InPoints[p0],e0,de)) {
  686. // both inside, emit p1
  687. EMIT(InPoints[p1],InUVs[p1]);
  688. } else {
  689. // edge going out->in, emit intersection and endpoint
  690. intersection = Intersect_Lines(InPoints[p0], InPoints[p1], e0, de);
  691. intersection_point = (1.0f - intersection) * InPoints[p0] + intersection * InPoints[p1];
  692. intersection_uv = (1.0f - intersection) * InUVs[p0] + intersection * InUVs[p1];
  693. EMIT(intersection_point,intersection_uv);
  694. EMIT(InPoints[p1],InUVs[p1]);
  695. }
  696. } else {
  697. if (In_Front_Of_Line(InPoints[p0], e0, de)) {
  698. // edge going in->out, emit intersection
  699. intersection = Intersect_Lines(InPoints[p0],InPoints[p1], e0, de);
  700. intersection_point = (1.0f - intersection) * InPoints[p0] + intersection * InPoints[p1];
  701. intersection_uv = (1.0f - intersection) * InUVs[p0] + intersection * InUVs[p1];
  702. EMIT(intersection_point,intersection_uv);
  703. }
  704. }
  705. // move to next edge
  706. p0 = p1;
  707. }
  708. return outnum;
  709. }
  710. inline int IntersectionClass::_Intersect_Triangles_Z(
  711. Vector3 ClipPoints[3],
  712. Vector3 TrianglePoints[3],
  713. Vector2 UV[3],
  714. Vector3 ClippedPoints[6],
  715. Vector2 ClippedUV[6]
  716. )
  717. {
  718. int count;
  719. Vector3 tmp_points[6];
  720. Vector2 tmp_uv[6];
  721. count = Clip_Triangle_To_LineXY(3,TrianglePoints,UV,ClippedPoints,ClippedUV,ClipPoints[0],ClipPoints[1]);
  722. count = Clip_Triangle_To_LineXY(count,ClippedPoints,ClippedUV,tmp_points,tmp_uv,ClipPoints[1],ClipPoints[2]);
  723. count = Clip_Triangle_To_LineXY(count,tmp_points,tmp_uv,ClippedPoints,ClippedUV,ClipPoints[2],ClipPoints[0]);
  724. return count;
  725. }
  726. /*
  727. ** This function will fill the passed array with the set of points & uv values that represent
  728. ** the boolean operation of the anding of the ClipPoints with the TrianglePoints. The UV values
  729. ** provided for the TrianglePoints triangle are used to generate accurate UV values for any
  730. ** new points created by this operation.
  731. ** This function returns the number of vertices it required to define the intersection.
  732. * /
  733. int IntersectionClass::_Intersect_Triangles_Z(
  734. Vector3 ClipPoints[3],
  735. Vector3 TrianglePoints[3],
  736. Vector2 UV[3],
  737. Vector3 ClippedPoints[6],
  738. Vector2 ClippedUV[6]
  739. )
  740. {
  741. // first, check to see if all triangle points are inside clip area
  742. // the point in polygon will drop any inside points to the clip triangle plane.
  743. bool inside[3];
  744. bool noclip;
  745. noclip = inside[0] = _Point_In_Polygon_Z(TrianglePoints[0], ClipPoints);
  746. noclip &= inside[1] = _Point_In_Polygon_Z(TrianglePoints[1], ClipPoints);
  747. noclip &= inside[2] = _Point_In_Polygon_Z(TrianglePoints[2], ClipPoints);
  748. // if all points are inside clip area, then copy the triangle points &
  749. // UV's to the destination & return 3 (the number of points in the clipped polygon).
  750. if(noclip) {
  751. ClippedPoints[0] = TrianglePoints[0];
  752. ClippedPoints[1] = TrianglePoints[1];
  753. ClippedPoints[2] = TrianglePoints[2];
  754. ClippedUV[0] = UV[0];
  755. ClippedUV[1] = UV[1];
  756. ClippedUV[2] = UV[2];
  757. return 3;
  758. }
  759. int points = 0; // number of output polygon points
  760. // not all uv triangle points are inside the clip triangle.
  761. // Test to see if any clip points are inside the uv triangle
  762. float alpha, beta;
  763. if(_Point_In_Polygon(ClipPoints[0], TrianglePoints[0], TrianglePoints[1], TrianglePoints[2], 0, 1, alpha, beta)) {
  764. ClippedPoints[points] = ClipPoints[0];
  765. Vector2 uv1 = UV[1] - UV[0];
  766. Vector2 uv2 = UV[2] - UV[0];
  767. ClippedUV[points++] = UV[0] + alpha * uv1 + beta * uv2;
  768. }
  769. if(_Point_In_Polygon(ClipPoints[1], TrianglePoints[0], TrianglePoints[1], TrianglePoints[2], 0, 1, alpha, beta)) {
  770. ClippedPoints[points] = ClipPoints[1];
  771. Vector2 uv1 = UV[1] - UV[0];
  772. Vector2 uv2 = UV[2] - UV[0];
  773. ClippedUV[points++] = UV[0] + alpha * uv1 + beta * uv2;
  774. }
  775. if(_Point_In_Polygon(ClipPoints[2], TrianglePoints[0], TrianglePoints[1], TrianglePoints[2], 0, 1, alpha, beta)) {
  776. ClippedPoints[points] = ClipPoints[2];
  777. Vector2 uv1 = UV[1] - UV[0];
  778. Vector2 uv2 = UV[2] - UV[0];
  779. ClippedUV[points++] = UV[0] + alpha * uv1 + beta * uv2;
  780. }
  781. // if all 3 clip points are inside the decal triangle then return
  782. if(points == 3)
  783. return;
  784. // The clip triangle does not fully contain the uv triangle, and the uv triangle
  785. // does not fully contain the clip triangle.
  786. // Intersect any edge which has at least one outside point with all of the clip edges.
  787. // First, determine which edges to test. Those points that are already clipped (by being inside)
  788. // are immediately copied to the clipped point & uv arrays.
  789. // these bools indicate which edges of the triangle to be clipped are to be tested.
  790. bool test_01 = false;
  791. bool test_02 = false;
  792. bool test_12 = false;
  793. if( inside[0] ) { ClippedPoints[points] = TrianglePoints[0]; ClippedUV[points++] = UV[0]; }
  794. else { test_01 = test_02 = true; }
  795. if( inside[1] ) { ClippedPoints[points] = TrianglePoints[1]; ClippedUV[points++] = UV[1]; }
  796. else { test_01 = test_12 = true; }
  797. if( inside[2] ) { ClippedPoints[points] = TrianglePoints[2]; ClippedUV[points++] = UV[2];}
  798. else { test_02 = test_12 = true; }
  799. // Now test each indicated segment.
  800. // Intersect_2D_Lines will interpolate the clipped UV values if an intersection occurs, and it
  801. // will also increment the points variable (passed as a reference).
  802. // Any intersections are stored in the passed ClippedPoints array.
  803. if(test_01) {
  804. _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[1],
  805. UV[0], UV[1],
  806. ClipPoints[0], ClipPoints[1],
  807. ClippedPoints,
  808. ClippedUV,
  809. points);
  810. _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[1],
  811. UV[0], UV[1],
  812. ClipPoints[0], ClipPoints[2],
  813. ClippedPoints,
  814. ClippedUV,
  815. points);
  816. _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[1],
  817. UV[0], UV[1],
  818. ClipPoints[1], ClipPoints[2],
  819. ClippedPoints,
  820. ClippedUV,
  821. points);
  822. }
  823. if(test_02) {
  824. _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[2],
  825. UV[0], UV[2],
  826. ClipPoints[0], ClipPoints[1],
  827. ClippedPoints,
  828. ClippedUV,
  829. points);
  830. _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[2],
  831. UV[0], UV[2],
  832. ClipPoints[0], ClipPoints[2],
  833. ClippedPoints,
  834. ClippedUV,
  835. points);
  836. _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[2],
  837. UV[0], UV[2],
  838. ClipPoints[1], ClipPoints[2],
  839. ClippedPoints,
  840. ClippedUV,
  841. points);
  842. }
  843. if(test_12) {
  844. _Intersect_Lines_Z( TrianglePoints[1], TrianglePoints[2],
  845. UV[1], UV[2],
  846. ClipPoints[0], ClipPoints[1],
  847. ClippedPoints,
  848. ClippedUV,
  849. points);
  850. _Intersect_Lines_Z( TrianglePoints[1], TrianglePoints[2],
  851. UV[1], UV[2],
  852. ClipPoints[0], ClipPoints[2],
  853. ClippedPoints,
  854. ClippedUV,
  855. points);
  856. _Intersect_Lines_Z( TrianglePoints[1], TrianglePoints[2],
  857. UV[1], UV[2],
  858. ClipPoints[1], ClipPoints[2],
  859. ClippedPoints,
  860. ClippedUV,
  861. points);
  862. }
  863. // If no intersections have occurred, then the triangle must be completely outside
  864. // the clipping area.
  865. /*
  866. // if it is determined that no intersections have occurred, then copy the clip triangle points
  867. // into the destination array and determine the correct UV values for the subset of the
  868. // triangle that was clipped.
  869. if(points == 0) {
  870. ClippedPoints[0] = ClipPoints[0];
  871. ClippedPoints[1] = ClipPoints[1];
  872. ClippedPoints[2] = ClipPoints[2];
  873. ClippedUV[0] = UV[0];
  874. ClippedUV[1] = UV[1];
  875. ClippedUV[2] = UV[2];
  876. return 3;
  877. }
  878. * /
  879. // points will be 0, 3, 4, 5 or 6
  880. if(!((points == 0) || (points == 3) || (points == 4) || (points == 5) || (points == 6))) {
  881. Debug.Print("points", points);
  882. return 0; //_Intersect_Triangles_Z( ClipPoints, TrianglePoints, UV, ClippedPoints, ClippedUV);
  883. }
  884. return points;
  885. }
  886. */
  887. #endif