Advertisement
Guest User

Untitled

a guest
Feb 13th, 2015
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. // C++ port of this demo code: http://jsfiddle.net/MadLittleMods/thcstaay/
  2. float approximateArcLengthOfBezierCurve(size_t controlPointListSize, Vector2 *controlPointListPointer, int resolution, Vector2 (*pointOnCurveFunc)(size_t, Vector2*, float)) {
  3.     // Resolution is the number of segments we use
  4.     resolution = resolution ? resolution : 500;
  5.    
  6.     float resultantArcLength = 0;
  7.     float arcLengthMap[resolution+1];
  8.  
  9.  
  10.     Vector2 controlPointList[controlPointListSize];
  11.     for(int i = 0; i < controlPointListSize; i++) {
  12.         controlPointList[i] = controlPointListPointer[i];
  13.     }
  14.  
  15.     Vector2 prevPoint = controlPointList[0];
  16.     Vector2 nextPoint;
  17.     int mapIndex = 0;
  18.     for(int i = 0; i < resolution; i++) {
  19.         float t = clamp(i*(1/resolution), 0, 1);
  20.         nextPoint = (*pointOnCurveFunc)(controlPointListSize, controlPointList, t);
  21.         resultantArcLength += distance(prevPoint, nextPoint);
  22.         prevPoint = nextPoint;
  23.  
  24.         arcLengthMap[mapIndex] = {
  25.             t: t,
  26.             arcLength: resultantArcLength
  27.         };
  28.         mapIndex++;
  29.     }
  30.     // Last stretch to the endpoint
  31.     nextPoint = controlPointList[controlPointList.length-1];
  32.     resultantArcLength += distance(prevPoint, nextPoint);
  33.     arcLengthMap[mapIndex] = {
  34.         t: 1,
  35.         arcLength: resultantArcLength
  36.     };
  37.     mapIndex++;
  38.  
  39.     return {
  40.         arcLength: resultantArcLength,
  41.         arcLengthMap: arcLengthMap
  42.     };
  43. }
  44.  
  45. float distance(Vector2 p0, Vector2 p1) {
  46.     return sqrt(pow(p1.x-p0.x, 2) + pow(p1.y-p0.y, 2));
  47. }
  48.  
  49. float clamp(float val, float minVal, float maxVal)
  50. {
  51.     float tempMax = max(val, minVal);
  52.     return min(tempMax, maxVal);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement