Oolite
Loading...
Searching...
No Matches
OOPolygonSprite.m
Go to the documentation of this file.
1/*
2
3OOPolygonSprite.m
4Oolite
5
6
7Copyright (C) 2009-2013 Jens Ayton
8
9Permission is hereby granted, free of charge, to any person obtaining a copy
10of this software and associated documentation files (the "Software"), to deal
11in the Software without restriction, including without limitation the rights
12to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13copies of the Software, and to permit persons to whom the Software is
14furnished to do so, subject to the following conditions:
15
16The above copyright notice and this permission notice shall be included in all
17copies or substantial portions of the Software.
18
19THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25SOFTWARE.
26
27*/
28
29/* Implementation note:
30
31 The polygon data is tesselated (on object creation) using a GLU tesselator.
32 Although GLU produces a mix of triangles, triangle fans and triangle
33 strips, we convert those to a single triangle soup since the polygons are
34 unlikely to be large enough that using multiple primitives would be a win.
35
36 Uniquing vertices and using indices, and using the same vertex array for
37 outline and filled mode, would in principle be more efficient, but not
38 worth the added complexity in the preprocessing given the simplicity of
39 the icons we're likely to encounter.
40*/
41
42#import "OOPolygonSprite.h"
45#import "OOMacroOpenGL.h"
46#import "OOMaths.h"
47#import "OOPointMaths.h"
48
49#ifndef APIENTRY
50#define APIENTRY
51#endif
52
53#define kCosMitreLimit 0.866f // Approximately cos(30 deg)
54
55@interface OOPolygonSprite (Private) <OOGraphicsResetClient>
56
57- (BOOL)loadPolygons:(NSArray*)dataArray outlineWidth:(float)outlineWidth;
58
59@end
60
61typedef struct
62{
63 GLfloat* data;
64 size_t count; // Number of vertices in use, i.e. half of number of data elements used.
65 size_t capacity; // Half of number of floats there is space for in data.
66 GLenum mode; // Current primitive mode.
67 size_t vCount; // Number of vertices so far in primitive.
68 NSPoint pending0, pending1; // Used for splitting GL_TRIANGLE_STRIP/GL_TRIANGLE_FAN primitives.
69 BOOL OK; // Set to false to indicate error.
70#ifndef NDEBUG
72 unsigned svgID;
73 NSString* name;
74 NSMutableString* debugSVG;
75#endif
77
78static NSArray* DataArrayToPoints(TessPolygonData* data, NSArray* dataArray);
79static NSArray* BuildOutlineContour(NSArray* dataArray, GLfloat width, BOOL inner);
80
81static void SubmitVertices(GLUtesselator* tesselator, TessPolygonData* polygonData, NSArray* contour);
82
83static BOOL GrowTessPolygonData(TessPolygonData* data, size_t capacityHint); // Returns true if capacity grew by at least one.
84static BOOL AppendVertex(TessPolygonData* data, NSPoint vertex);
85
86#ifndef NDEBUG
87static void SVGDumpBegin(TessPolygonData* data);
88static void SVGDumpEnd(TessPolygonData* data);
89static void SVGDumpBeginGroup(TessPolygonData* data, NSString* name);
90static void SVGDumpEndGroup(TessPolygonData* data);
91static void SVGDumpAppendBaseContour(TessPolygonData* data, NSArray* points);
92static void SVGDumpBeginPrimitive(TessPolygonData* data);
93static void SVGDumpEndPrimitive(TessPolygonData* data);
94static void SVGDumpAppendTriangle(TessPolygonData* data, NSPoint v0, NSPoint v1, NSPoint v2);
95#else
96#define SVGDumpEnd(data) \
97 do { \
98 } while (0)
99#define SVGDumpBeginGroup(data, name) \
100 do { \
101 } while (0)
102#define SVGDumpEndGroup(data) \
103 do { \
104 } while (0)
105#define SVGDumpAppendBaseContour(data, points) \
106 do { \
107 } while (0)
108#define SVGDumpBeginPrimitive(data) \
109 do { \
110 } while (0)
111#define SVGDumpEndPrimitive(data) \
112 do { \
113 } while (0)
114#define SVGDumpAppendTriangle(data, v0, v1, v2) \
115 do { \
116 } while (0)
117#endif
118
119static void APIENTRY TessBeginCallback(GLenum type, void* polygonData);
120static void APIENTRY TessVertexCallback(void* vertexData, void* polygonData);
121static void APIENTRY TessCombineCallback(GLdouble coords[3], void* vertexData[4], GLfloat weight[4], void** outData, void* polygonData);
122static void APIENTRY TessEndCallback(void* polygonData);
123
124static void APIENTRY ErrorCallback(GLenum error, void* polygonData);
125
126// this is needed to maintain compatibility with GCC 14+
127typedef GLvoid (*TessFuncPtr)();
128
129@implementation OOPolygonSprite
130
131- (id)initWithDataArray:(NSArray*)dataArray outlineWidth:(GLfloat)outlineWidth name:(NSString*)name
132{
133 if ((self = [super init])) {
134#ifndef NDEBUG
135 _name = [name copy];
136#endif
137
138 if ([dataArray count] == 0) {
139 [self release];
140 return nil;
141 }
142
143 // Normalize data to array-of-arrays form.
144 if (![[dataArray objectAtIndex:0] isKindOfClass:[NSArray class]]) {
145 dataArray = [NSArray arrayWithObject:dataArray];
146 }
147 if (![self loadPolygons:dataArray outlineWidth:outlineWidth]) {
148 [self release];
149 return nil;
150 }
151
153 }
154
155 return self;
156}
157
158- (void)dealloc
159{
161
162#ifndef NDEBUG
163 DESTROY(_name);
164#endif
165 free(_solidData);
166 free(_outlineData);
167
168 [super dealloc];
169}
170
171#ifndef NDEBUG
173{
174 return _name;
175}
176#endif
177
178- (void)drawWithData:(GLfloat*)data count:(size_t)count VBO:(GLuint*)vbo
179{
180 if (count == 0)
181 return;
182 NSParameterAssert(vbo != NULL && data != NULL);
183
186
187#if OO_USE_VBO
189
190 if (useVBO) {
191 if (*vbo == 0) {
192 OOGL(glGenBuffersARB(1, vbo));
193 if (*vbo != 0) {
194 OOGL(glBindBufferARB(GL_ARRAY_BUFFER, *vbo));
195 OOGL(glBufferDataARB(GL_ARRAY_BUFFER, sizeof(GLfloat) * count * 2, data, GL_STATIC_DRAW));
196 }
197 } else {
198 OOGL(glBindBufferARB(GL_ARRAY_BUFFER, *vbo));
199 }
200 if (*vbo != 0)
201 data = NULL; // Must pass NULL pointer to glVertexPointer to use VBO.
202 }
203#endif
204
205 OOGL(glEnableClientState(GL_VERTEX_ARRAY));
206 OOGL(glVertexPointer(2, GL_FLOAT, 0, data));
207 OOGL(glDrawArrays(GL_TRIANGLES, 0, count));
208 OOGL(glDisableClientState(GL_VERTEX_ARRAY));
209
210#if OO_USE_VBO
211 if (useVBO)
212 OOGL(glBindBufferARB(GL_ARRAY_BUFFER, 0));
213#endif
214
216 OOCheckOpenGLErrors(@"OOPolygonSprite after rendering %@", self);
217}
218
220{
221#if !OO_USE_VBO
222 GLuint _solidVBO; // Unusued
223#endif
224
225 [self drawWithData:_solidData
226 count:_solidCount
227 VBO:&_solidVBO];
228}
229
231{
232#if !OO_USE_VBO
233 GLuint _outlineVBO; // Unusued
234#endif
235
236 [self drawWithData:_outlineData
237 count:_outlineCount
238 VBO:&_outlineVBO];
239}
240
242{
243#if OO_USE_VBO
245
246 if (_solidVBO != 0)
247 glDeleteBuffersARB(1, &_solidVBO);
248 if (_outlineVBO != 0)
249 glDeleteBuffersARB(1, &_outlineVBO);
250
251 _solidVBO = 0;
252 _outlineVBO = 0;
253#endif
254}
255
256// FIXME: this method is absolutely horrible.
257- (BOOL)loadPolygons:(NSArray*)dataArray outlineWidth:(float)outlineWidth
258{
259 NSParameterAssert(dataArray != nil);
260
261 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
262 GLUtesselator* tesselator = NULL;
263
264 TessPolygonData polygonData;
265 memset(&polygonData, 0, sizeof polygonData);
266 polygonData.OK = YES;
267#ifndef NDEBUG
268 polygonData.name = _name;
269 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"polygon-sprite-dump-svg"])
270 SVGDumpBegin(&polygonData);
271#endif
272
273 // For efficiency, grow to more than big enough for most cases to avoid regrowing.
274 if (!GrowTessPolygonData(&polygonData, 100)) {
275 polygonData.OK = NO;
276 goto END;
277 }
278
279 tesselator = gluNewTess();
280 if (tesselator == NULL) {
281 polygonData.OK = NO;
282 goto END;
283 }
284
285 dataArray = DataArrayToPoints(&polygonData, dataArray);
286
287 /*** Tesselate polygon fill ***/
288 gluTessCallback(tesselator, GLU_TESS_BEGIN_DATA, (TessFuncPtr)TessBeginCallback);
289 gluTessCallback(tesselator, GLU_TESS_VERTEX_DATA, (TessFuncPtr)TessVertexCallback);
290 gluTessCallback(tesselator, GLU_TESS_END_DATA, (TessFuncPtr)TessEndCallback);
291 gluTessCallback(tesselator, GLU_TESS_ERROR_DATA, (TessFuncPtr)ErrorCallback);
292 gluTessCallback(tesselator, GLU_TESS_COMBINE_DATA, (TessFuncPtr)TessCombineCallback);
293
294 gluTessBeginPolygon(tesselator, &polygonData);
295 SVGDumpBeginGroup(&polygonData, @"Fill");
296
297 NSUInteger contourCount = [dataArray count], contourIndex;
298 for (contourIndex = 0; contourIndex < contourCount && polygonData.OK; contourIndex++) {
299 NSArray* contour = [dataArray oo_arrayAtIndex:contourIndex];
300 if (contour == nil) {
301 polygonData.OK = NO;
302 break;
303 }
304
305 SubmitVertices(tesselator, &polygonData, contour);
306 }
307
308 gluTessEndPolygon(tesselator);
309 SVGDumpEndGroup(&polygonData);
310
311 if (polygonData.OK) {
312 _solidCount = polygonData.count;
313
314 if (_solidCount != 0) {
315 _solidData = realloc(polygonData.data, polygonData.count * sizeof(GLfloat) * 2);
316 if (_solidData != NULL)
317 polygonData.data = NULL; // realloc succeded.
318 else {
319 // Unlikely, but legal: realloc failed to shrink buffer.
320 _solidData = polygonData.data;
321 if (_solidData == NULL)
322 polygonData.OK = NO;
323 }
324 } else {
325 // Empty polygon.
326 _solidData = NULL;
327 }
328 }
329 if (!polygonData.OK)
330 goto END;
331
332 /*** Tesselate polygon outline ***/
333 gluDeleteTess(tesselator);
334 tesselator = gluNewTess();
335 if (tesselator == NULL) {
336 polygonData.OK = NO;
337 goto END;
338 }
339
340 polygonData.count = 0;
341 polygonData.capacity = 0;
342 if (!GrowTessPolygonData(&polygonData, 100)) {
343 polygonData.OK = NO;
344 goto END;
345 }
346#ifndef NDEBUG
347 polygonData.generatingOutline = YES;
348#endif
349
350 gluTessCallback(tesselator, GLU_TESS_BEGIN_DATA, (TessFuncPtr)TessBeginCallback);
351 gluTessCallback(tesselator, GLU_TESS_VERTEX_DATA, (TessFuncPtr)TessVertexCallback);
352 gluTessCallback(tesselator, GLU_TESS_END_DATA, (TessFuncPtr)TessEndCallback);
353 gluTessCallback(tesselator, GLU_TESS_ERROR_DATA, (TessFuncPtr)ErrorCallback);
354 gluTessCallback(tesselator, GLU_TESS_COMBINE_DATA, (TessFuncPtr)TessCombineCallback);
355 gluTessProperty(tesselator, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_POSITIVE);
356
357 gluTessBeginPolygon(tesselator, &polygonData);
358 SVGDumpBeginGroup(&polygonData, @"Outline");
359
360 outlineWidth *= 0.5f; // Half the width in, half the width out.
361 contourCount = [dataArray count];
362 for (contourIndex = 0; contourIndex < contourCount && polygonData.OK; contourIndex++) {
363 NSArray* contour = [dataArray oo_arrayAtIndex:contourIndex];
364 if (contour == nil) {
365 polygonData.OK = NO;
366 break;
367 }
368
369 SubmitVertices(tesselator, &polygonData, BuildOutlineContour(contour, outlineWidth, NO));
370 SubmitVertices(tesselator, &polygonData, BuildOutlineContour(contour, outlineWidth, YES));
371 }
372
373 gluTessEndPolygon(tesselator);
374 SVGDumpEndGroup(&polygonData);
375
376 if (polygonData.OK) {
377 if (polygonData.count != 0) {
378 _outlineCount = polygonData.count;
379 _outlineData = realloc(polygonData.data, polygonData.count * sizeof(GLfloat) * 2);
380 if (_outlineData != NULL)
381 polygonData.data = NULL; // realloc succeded.
382 else {
383 // Unlikely, but legal: realloc failed to shrink buffer.
384 _outlineData = polygonData.data;
385 if (_outlineData == NULL)
386 polygonData.OK = NO;
387 }
388 } else {
389 // Empty polygon.
390 _outlineCount = 0;
391 _outlineData = NULL;
392 }
393 }
394
395END:
396 SVGDumpEnd(&polygonData);
397 free(polygonData.data);
398 gluDeleteTess(tesselator);
399 [pool release];
400#ifndef NDEBUG
401 DESTROY(polygonData.debugSVG);
402#endif
403 return polygonData.OK;
404}
405
406@end
407
408static void SubmitVertices(GLUtesselator* tesselator, TessPolygonData* polygonData, NSArray* contour)
409{
410 NSUInteger vertexCount = [contour count], vertexIndex;
411 if (vertexCount > 2) {
412 gluTessBeginContour(tesselator);
413
414 for (vertexIndex = 0; vertexIndex < vertexCount && polygonData->OK; vertexIndex++) {
415 NSValue* pointValue = [contour objectAtIndex:vertexIndex];
416 NSPoint p = [pointValue pointValue];
417 GLdouble vert[3] = { p.x, p.y, 0.0 };
418
419 gluTessVertex(tesselator, vert, pointValue);
420 }
421
422 gluTessEndContour(tesselator);
423 }
424}
425
426static NSArray* DataArrayToPoints(TessPolygonData* data, NSArray* dataArray)
427{
428 /* This converts an icon definition in the form of an array of array of
429 numbers to internal data in the form of an array of arrays of NSValues
430 containing NSPoint data. In addition to repacking the data, it performs
431 the following data processing:
432 * Sequences of duplicate vertices are removed (including across the
433 beginning and end, in case of manually closed contours).
434 * Vertices containing nans or infinities are skipped, Just In Case.
435 * The signed area of each contour is calculated; if it is negative,
436 the contour is clockwise, and we need to flip it.
437 */
438
439 SVGDumpBeginGroup(data, @"Base contours");
440
441 NSUInteger polyIter, polyCount = [dataArray count];
442 NSArray* subArrays[polyCount];
443
444 for (polyIter = 0; polyIter < polyCount; polyIter++) {
445 NSArray* polyDef = [dataArray objectAtIndex:polyIter];
446 NSUInteger vertIter, vertCount = [polyDef count] / 2;
447 NSMutableArray* newPolyDef = [NSMutableArray arrayWithCapacity:vertCount];
448 CGFloat area = 0;
449
450 CGFloat oldX = [polyDef oo_doubleAtIndex:(vertCount - 1) * 2];
451 CGFloat oldY = [polyDef oo_doubleAtIndex:(vertCount - 1) * 2 + 1];
452
453 for (vertIter = 0; vertIter < vertCount; vertIter++) {
454 CGFloat x = [polyDef oo_doubleAtIndex:vertIter * 2];
455 CGFloat y = [polyDef oo_doubleAtIndex:vertIter * 2 + 1];
456
457 // Skip bad or duplicate vertices.
458 if (x == oldX && y == oldY)
459 continue;
460 if (isnan(x) || isnan(y))
461 continue;
462 if (!isfinite(x) || !isfinite(y))
463 continue;
464
465 area += x * oldY - oldX * y;
466
467 oldX = x;
468 oldY = y;
469
470 [newPolyDef addObject:[NSValue valueWithPoint:NSMakePoint(x, y)]];
471 }
472
473 // Eliminate duplicates at ends - the initialization of oldX and oldY will catch one pair, but not extra-silly cases.
474 while ([newPolyDef count] > 1 && [[newPolyDef objectAtIndex:0] isEqual:[newPolyDef lastObject]]) {
475 [newPolyDef removeLastObject];
476 }
477
478 if (area >= 0) {
479 subArrays[polyIter] = newPolyDef;
480 } else {
481 subArrays[polyIter] = [[newPolyDef reverseObjectEnumerator] allObjects];
482 }
483
484 SVGDumpAppendBaseContour(data, subArrays[polyIter]);
485 }
486
487 SVGDumpEndGroup(data);
488 return [NSArray arrayWithObjects:subArrays count:polyCount];
489}
490
491static NSArray* BuildOutlineContour(NSArray* dataArray, GLfloat width, BOOL inner)
492{
493 NSUInteger i, count = [dataArray count];
494 if (count < 2)
495 return dataArray;
496
497 /*
498 Generate inner or outer boundary for a contour, offset by the specified
499 width inwards/outwards from the line. At anticlockwise (convex) corners
500 sharper than acos(kCosMitreLimit), the corner is mitred, i.e. an
501 additional line segment is generated so the outline doesn't protrude
502 arbitratrily far.
503
504 Overview of the maths:
505 For each vertex, we consider a normalized vector A from the previous
506 vertex and a normalized vector B to the next vertex. (These are always
507 defined since the polygons are closed.)
508
509 The dot product of A and B is the cosine of the angle, which we compare
510 to kCosMitreLimit to determine mitreing. If the dot product is exactly
511 1, the vectors are antiparallel and we have a cap; the mitreing case
512 handles this implicitly. (The non-mitreing case would result in a
513 divide-by-zero.)
514
515 Non-mitreing case:
516 To position the vertex, we need a vector N normal to the corner.
517 We observe that A + B is tangent to the corner, and a 90 degree
518 rotation in 2D is trivial. The offset along this line is
519 proportional to the secant of the angle between N and the 90 degree
520 rotation of A (or B; the angle is by definition the same), or
521 width / (N dot rA).
522 Since both N and rA are rotated by ninety degrees in the same
523 direction, we can cut out both rotations (i.e., using the tangent
524 and A) and get the same result.
525
526 Mitreing case:
527 The two new vertices are the original vertex offset by scale along
528 the ninety-degree rotation of A and B respectively.
529 */
530
531 NSPoint prev, current, next;
532 if (inner) {
533 prev = [[dataArray objectAtIndex:0] pointValue];
534 current = [[dataArray objectAtIndex:count - 1] pointValue];
535 next = [[dataArray objectAtIndex:count - 2] pointValue];
536 } else {
537 prev = [[dataArray objectAtIndex:count - 1] pointValue];
538 current = [[dataArray objectAtIndex:0] pointValue];
539 next = [[dataArray objectAtIndex:1] pointValue];
540 }
541
542 NSMutableArray* result = [NSMutableArray arrayWithCapacity:count];
543
544 for (i = 0; i < count; i++) {
545 NSPoint a = PtNormal(PtSub(current, prev));
546 NSPoint b = PtNormal(PtSub(next, current));
547
548 CGFloat dot = PtDot(a, b);
549 BOOL clockwise = PtCross(a, b) < 0.0f;
550
551 if (-dot < kCosMitreLimit || !clockwise) {
552 // Non-mitreing case.
553 NSPoint t = PtNormal(PtAdd(a, b));
554 NSPoint v = PtScale(PtRotACW(t), width / PtDot(t, a));
555
556 if (!isnan(v.x) && !isnan(v.y)) {
557 [result addObject:[NSValue valueWithPoint:PtAdd(v, current)]];
558 }
559 } else {
560 // Mitreing case.
561 NSPoint v1 = PtScale(PtAdd(PtRotACW(a), a), width);
562 NSPoint v2 = PtScale(PtSub(PtRotACW(b), b), width);
563
564 if (!isnan(v1.x) && !isnan(v1.y)) {
565 [result addObject:[NSValue valueWithPoint:PtAdd(v1, current)]];
566 }
567 if (!isnan(v2.x) && !isnan(v2.y)) {
568 [result addObject:[NSValue valueWithPoint:PtAdd(v2, current)]];
569 }
570 }
571
572 prev = current;
573 current = next;
574
575 if (inner) {
576 next = [[dataArray objectAtIndex:(count * 2 - 3 - i) % count] pointValue];
577 } else {
578 next = [[dataArray objectAtIndex:(i + 2) % count] pointValue];
579 }
580 }
581
582 return result;
583}
584
585static BOOL GrowTessPolygonData(TessPolygonData* data, size_t capacityHint)
586{
587 NSCParameterAssert(data != NULL);
588
589 size_t minCapacity = data->capacity + 1;
590 size_t desiredCapacity = MAX(capacityHint, minCapacity);
591 size_t newCapacity = 0;
592 GLfloat* newData = realloc(data->data, desiredCapacity * sizeof(GLfloat) * 2);
593 if (newData != NULL) {
594 newCapacity = desiredCapacity;
595 } else {
596 desiredCapacity = minCapacity;
597 newData = realloc(data->data, desiredCapacity * sizeof(GLfloat) * 2);
598 if (newData != NULL)
599 newCapacity = desiredCapacity;
600 }
601
602 if (newData == NULL)
603 return NO;
604
605 NSCAssert(newCapacity > data->capacity, @"Buffer regrow logic error");
606
607 data->data = newData;
608 data->capacity = newCapacity;
609 return YES;
610}
611
612static BOOL AppendVertex(TessPolygonData* data, NSPoint vertex)
613{
614 NSCParameterAssert(data != NULL);
615
616 if (data->capacity == data->count && !GrowTessPolygonData(data, data->capacity * 2))
617 return NO;
618
619 data->data[data->count * 2] = vertex.x;
620 data->data[data->count * 2 + 1] = vertex.y;
621 data->count++;
622 return YES;
623}
624
625static void APIENTRY TessBeginCallback(GLenum type, void* polygonData)
626{
627 TessPolygonData* data = polygonData;
628 NSCParameterAssert(data != NULL);
629
630 data->mode = type;
631 data->vCount = 0;
632
634}
635
636static void APIENTRY TessVertexCallback(void* vertexData, void* polygonData)
637{
638 TessPolygonData* data = polygonData;
639 NSValue* vertValue = vertexData;
640 NSCParameterAssert(vertValue != NULL && data != NULL);
641 if (!data->OK)
642 return;
643
644 NSPoint p = [vertValue pointValue];
645 NSPoint vertex = { p.x, p.y };
646 size_t vCount = data->vCount++;
647
648 switch (data->mode) {
649 case GL_TRIANGLES:
650 data->OK = AppendVertex(data, vertex);
651#ifndef NDEBUG
652 switch (vCount % 3) {
653 case 0:
654 data->pending0 = vertex;
655 break;
656
657 case 1:
658 data->pending1 = vertex;
659 break;
660
661 case 2:
662 SVGDumpAppendTriangle(data, data->pending0, data->pending1, vertex);
663 }
664#endif
665 break;
666
667 case GL_TRIANGLE_FAN:
668 if (vCount == 0)
669 data->pending0 = vertex;
670 else if (vCount == 1)
671 data->pending1 = vertex;
672 else {
673 data->OK = AppendVertex(data, data->pending0) && AppendVertex(data, data->pending1) && AppendVertex(data, vertex);
674 SVGDumpAppendTriangle(data, data->pending0, data->pending1, vertex);
675 data->pending1 = vertex;
676 }
677 break;
678
679 case GL_TRIANGLE_STRIP:
680 if (vCount == 0)
681 data->pending0 = vertex;
682 else if (vCount == 1)
683 data->pending1 = vertex;
684 else {
685 /* In order to produce consistent winding, the vertex->triangle
686 order for GL_TRIANGLE_STRIP is:
687 0, 1, 2
688 2, 1, 3
689 2, 3, 4
690 4, 3, 5
691 4, 5, 6
692 6, 5, 7
693 6, 7, 8
694
695 Vertices 0 and 1 are special-cased above, and the first
696 time we get here it's time for the first triangle, which
697 is pending0, pending1, v. v (i.e., vertex 2) then goes into
698 pending0.
699 For the second triangle, the triangle is again pending0,
700 pending1, v, and we then put v (i.e., vertex 3) into
701 pending1.
702 The third triangle follows the same pattern as the first,
703 and the fourthe the same as the second.
704 In other words, after storing each triangle, v goes into
705 pending0 for even vertex indicies, and pending1 for odd
706 vertex indices.
707 */
708 data->OK = AppendVertex(data, data->pending0) && AppendVertex(data, data->pending1) && AppendVertex(data, vertex);
709 SVGDumpAppendTriangle(data, data->pending0, data->pending1, vertex);
710 if ((vCount % 2) == 0)
711 data->pending0 = vertex;
712 else
713 data->pending1 = vertex;
714 }
715 break;
716
717 default:
718 OOLog(@"polygonSprite.tesselate.error", @"Unexpected tesselator primitive mode %u.", data->mode);
719 data->OK = NO;
720 }
721}
722
723static void APIENTRY TessCombineCallback(GLdouble coords[3], void* vertexData[4], GLfloat weight[4], void** outData, void* polygonData)
724{
725 NSPoint point = { coords[0], coords[1] };
726 *outData = [NSValue valueWithPoint:point];
727}
728
729static void APIENTRY TessEndCallback(void* polygonData)
730{
731 TessPolygonData* data = polygonData;
732 NSCParameterAssert(data != NULL);
733
734 data->mode = 0;
735 data->vCount = 0;
736
738}
739
740static void APIENTRY ErrorCallback(GLenum error, void* polygonData)
741{
742 TessPolygonData* data = polygonData;
743 NSCParameterAssert(data != NULL);
744
745 NSString* name = @"";
746#ifndef NDEBUG
747 name = [NSString stringWithFormat:@" \"%@\"", data->name];
748#endif
749
750 char* errStr = (char*)gluErrorString(error);
751
752 OOLog(@"polygonSprite.tesselate.error", @"Error %s (%u) while tesselating polygon%@.", errStr, error, name);
753 data->OK = NO;
754}
755
756#ifndef NDEBUG
757#import "ResourceManager.h"
758#import "legacy_random.h"
759
761{
762 DESTROY(data->debugSVG);
763 data->debugSVG = [[NSMutableString alloc] initWithString:
764 @"<?xml version=\"1.0\" standalone=\"no\"?>\n"
765 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"
766 "<svg viewBox=\"-5 -5 10 10\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n"
767 "\t<desc>Oolite polygon sprite debug dump.</desc>\n"
768 "\t\n"];
769}
770
771static void SVGDumpEnd(TessPolygonData* data)
772{
773 if (data->debugSVG == nil)
774 return;
775
776 [data->debugSVG appendString:@"</svg>\n"];
777 [ResourceManager writeDiagnosticString:data->debugSVG toFileNamed:[NSString stringWithFormat:@"Polygon Sprites/%@.svg", data->name]];
778 DESTROY(data->debugSVG);
779}
780
781static void SVGDumpBeginGroup(TessPolygonData* data, NSString* name)
782{
783 if (data->debugSVG == nil)
784 return;
785
786 [data->debugSVG appendFormat:@"\t<g id=\"%@ %u\">\n", name, data->svgID++];
787}
788
790{
791 if (data->debugSVG == nil)
792 return;
793 [data->debugSVG appendString:@"\t</g>\n"];
794}
795
796static void SVGDumpAppendBaseContour(TessPolygonData* data, NSArray* points)
797{
798 if (data->debugSVG == nil)
799 return;
800
801 NSString* groupName = [NSString stringWithFormat:@"contour %u", data->svgID++];
802 [data->debugSVG appendFormat:@"\t\t<g id=\"%@\" stroke=\"#BBB\" fill=\"none\">\n\t\t<path stroke-width=\"0.05\" d=\"", groupName];
803
804 NSUInteger i, count = [points count];
805 for (i = 0; i < count; i++) {
806 NSPoint p = [[points objectAtIndex:i] pointValue];
807 [data->debugSVG appendFormat:@"%c %f %f ", (i == 0) ? 'M' : 'L', p.x, -p.y];
808 }
809
810 // Close and add a circle at the first vertex. (SVG has support for end markers, but this isn’t reliable across implementations.)
811 NSPoint p = [[points objectAtIndex:0] pointValue];
812 [data->debugSVG appendFormat:@"z\"/>\n\t\t\t<circle cx=\"%f\" cy=\"%f\" r=\"0.1\" fill=\"#BBB\" stroke=\"none\"/>\n\t\t</g>\n", p.x, -p.y];
813}
814
816{
817 if (data->debugSVG == nil)
818 return;
819
820 NSString* groupName = @"Unknown primitive";
821 switch (data->mode) {
822 case GL_TRIANGLES:
823 groupName = @"Triangle soup";
824 break;
825
826 case GL_TRIANGLE_FAN:
827 groupName = @"Triangle fan";
828 break;
829
830 case GL_TRIANGLE_STRIP:
831 groupName = @"Triangle strip";
832 break;
833 }
834 groupName = [groupName stringByAppendingFormat:@" %u", data->svgID++];
835
836 // Pick random colour for the primitive.
837 uint8_t red = (Ranrot() & 0x3F) + 0x20;
838 uint8_t green = (Ranrot() & 0x3F) + 0x20;
839 uint8_t blue = (Ranrot() & 0x3F) + 0x20;
840 if (!data->generatingOutline) {
841 red += 0x80;
842 green += 0x80;
843 blue += 0x80;
844 }
845
846 [data->debugSVG appendFormat:@"\t\t<g id=\"%@\" fill=\"#%2X%2X%2X\" fill-opacity=\"0.3\" stroke=\"%@\" stroke-width=\"0.01\">\n", groupName, red, green, blue, data->generatingOutline ? @"#060" : @"#008"];
847}
848
850{
851 if (data->debugSVG == nil)
852 return;
853 [data->debugSVG appendString:@"\t\t</g>\n"];
854}
855
856static void SVGDumpAppendTriangle(TessPolygonData* data, NSPoint v0, NSPoint v1, NSPoint v2)
857{
858 if (data->debugSVG == nil)
859 return;
860 [data->debugSVG appendFormat:@"\t\t\t<path d=\"M %f %f L %f %f L %f %f z\"/>\n", v0.x, -v0.y, v1.x, -v1.y, v2.x, -v2.y];
861}
862#endif
#define DESTROY(x)
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define OO_ENTER_OPENGL()
#define MAX(A, B)
Definition OOMaths.h:94
@ OPENGL_STATE_OVERLAY
Definition OOOpenGL.h:124
#define OOVerifyOpenGLState()
Definition OOOpenGL.h:133
BOOL OOCheckOpenGLErrors(NSString *format,...)
Definition OOOpenGL.m:38
#define OOSetOpenGLState(STATE)
Definition OOOpenGL.h:132
#define OOGL(statement)
Definition OOOpenGL.h:262
unsigned count
OOINLINE CGFloat PtDot(NSPoint a, NSPoint b)
OOINLINE NSPoint PtScale(NSPoint p, CGFloat scale)
OOINLINE NSPoint PtSub(NSPoint a, NSPoint b)
OOINLINE NSPoint PtRotACW(NSPoint p)
OOINLINE NSPoint PtNormal(NSPoint p)
OOINLINE CGFloat PtCross(NSPoint a, NSPoint b)
OOINLINE NSPoint PtAdd(NSPoint a, NSPoint b)
Definition OOPointMaths.h:5
static void APIENTRY TessVertexCallback(void *vertexData, void *polygonData)
static void APIENTRY TessEndCallback(void *polygonData)
static BOOL AppendVertex(TessPolygonData *data, NSPoint vertex)
static void SVGDumpEndPrimitive(TessPolygonData *data)
static void APIENTRY TessBeginCallback(GLenum type, void *polygonData)
static void SVGDumpBeginGroup(TessPolygonData *data, NSString *name)
static void SVGDumpAppendTriangle(TessPolygonData *data, NSPoint v0, NSPoint v1, NSPoint v2)
static NSArray * DataArrayToPoints(TessPolygonData *data, NSArray *dataArray)
#define APIENTRY
GLvoid(* TessFuncPtr)()
static void SubmitVertices(GLUtesselator *tesselator, TessPolygonData *polygonData, NSArray *contour)
static void APIENTRY ErrorCallback(GLenum error, void *polygonData)
static void SVGDumpBeginPrimitive(TessPolygonData *data)
static void APIENTRY TessCombineCallback(GLdouble coords[3], void *vertexData[4], GLfloat weight[4], void **outData, void *polygonData)
static void SVGDumpAppendBaseContour(TessPolygonData *data, NSArray *points)
static NSArray * BuildOutlineContour(NSArray *dataArray, GLfloat width, BOOL inner)
static void SVGDumpBegin(TessPolygonData *data)
static void SVGDumpEndGroup(TessPolygonData *data)
static void SVGDumpEnd(TessPolygonData *data)
static BOOL GrowTessPolygonData(TessPolygonData *data, size_t capacityHint)
#define kCosMitreLimit
return nil
float y
float x
void registerClient:(id< OOGraphicsResetClient > client)
void unregisterClient:(id< OOGraphicsResetClient > client)
OOGraphicsResetManager * sharedManager()
OOOpenGLExtensionManager * sharedManager()
void drawWithData:count:VBO:(GLfloat *data, [count] size_t count, [VBO] GLuint *vbo)
GLfloat * _outlineData
NSString * descriptionComponents()
BOOL writeDiagnosticString:toFileNamed:(NSString *string,[toFileNamed] NSString *name)
unsigned Ranrot(void)
NSMutableString * debugSVG