aboutsummaryrefslogtreecommitdiff
path: root/PhysX_3.4/Samples/SampleBase/RenderClothActor.cpp
blob: 65f0b642557063b5d564aac12b068a2b1e5f0037 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.  

#include "PxPhysXConfig.h"
#if PX_USE_CLOTH_API

#include "RenderClothActor.h"
#include "RenderCapsuleActor.h"
#include "RenderSphereActor.h"
#include "RenderMeshActor.h"
#include "RenderMaterial.h"
#include "RendererMeshShape.h"
#include "RendererClothShape.h"
#include "RendererCapsuleShape.h"
#include "PhysXSample.h"
#include "foundation/PxBounds3.h"

#include "cloth/PxClothParticleData.h"
#include "cloth/PxCloth.h"

#include "task/PxTask.h"

#include "extensions/PxSmoothNormals.h"

using namespace SampleRenderer;

/// These functions can probably move to PxToolkit or PxExtension
namespace 
{

// create uv from planar projection onto xz plane (where most cloth grids are created)
void createUVWithPlanarProjection(PxReal* uvs, PxU32 numVerts, const PxVec3* verts)
{
	PxBounds3 bounds = PxBounds3::empty();

    for(PxU32 i = 0; i < numVerts; i++)
		bounds.include(verts[i]);

	PxVec3 dim = bounds.getDimensions();
	PxReal minVal = PX_MAX_REAL;
	PxU32 minAxis = 0;

	// find smallest axis
	if (dim.x < minVal) { minVal = dim.x; minAxis = 0; }
	if (dim.y < minVal) { minVal = dim.y; minAxis = 1; }
	if (dim.z < minVal) { minVal = dim.z; minAxis = 2; }

	PxU32 uAxis = 0, vAxis = 1;
	switch (minAxis)
	{
		case 0: uAxis = 1; vAxis = 2; break; 
		case 1: uAxis = 0; vAxis = 2; break; 
		case 2: uAxis = 0; vAxis = 1; break; 
	}
	
	const float sizeU = dim[uAxis];
	const float sizeV = dim[vAxis];
	const float minU = bounds.minimum[uAxis];
	const float minV = bounds.minimum[vAxis];

	for (PxU32 i = 0; i < numVerts; ++i)
    {
        uvs[i*2+0] = (verts[i][uAxis] - minU) / sizeU;
        uvs[i*2+1] = 1.f - (verts[i][vAxis]-minV) / sizeV;
    }
    
}

// extract current cloth particle position from PxCloth
// verts is supposed to have been pre-allocated to be at least size of particle array
bool getVertsFromCloth(PxVec3* verts, const PxCloth& cloth)
{
	PxClothParticleData* readData = const_cast<PxCloth&>(cloth).lockParticleData();
    if (!readData)
        return false;

    // copy vertex positions
    PxU32 numVerts = cloth.getNbParticles();
	for (PxU32 i = 0; i < numVerts; ++i)
		verts[i] = readData->particles[i].pos;

	readData->unlock();

    return true;
}

// copy face structure from PxClothMeshDesc
PxU16* createFacesFromMeshDesc(const PxClothMeshDesc& desc)
{
    PxU32 numTriangles = desc.triangles.count;
	PxU32 numQuads = desc.quads.count;

    PxU16* faces = (PxU16*)SAMPLE_ALLOC(sizeof(PxU16)* (numTriangles*3 + numQuads*6));
	PxU16* fIt = faces;

    PxU8* triangles = (PxU8*)desc.triangles.data;
    for (PxU32 i = 0; i < numTriangles; i++)
    {
        if (desc.flags & PxMeshFlag::e16_BIT_INDICES)
        {
            PxU16* triangle = (PxU16*)triangles;
            *fIt++ = triangle[ 0 ];
            *fIt++ = triangle[ 1 ];
            *fIt++ = triangle[ 2 ];
        } 
        else
        {
            PxU32* triangle = (PxU32*)triangles;
            *fIt++ = triangle[ 0 ];
            *fIt++ = triangle[ 1 ];
            *fIt++ = triangle[ 2 ];
        }
        triangles += desc.triangles.stride;
    }

	PxU8* quads = (PxU8*)desc.quads.data;
	for (PxU32 i = 0; i < numQuads; i++)
	{
		if (desc.flags & PxMeshFlag::e16_BIT_INDICES)
		{
			PxU16* quad = (PxU16*)quads;
			*fIt++ = quad[ 0 ];
			*fIt++ = quad[ 1 ];
			*fIt++ = quad[ 2 ];
			*fIt++ = quad[ 2 ];
			*fIt++ = quad[ 3 ];
			*fIt++ = quad[ 0 ];
		} 
		else
		{
			PxU32* quad = (PxU32*)quads;
			*fIt++ = quad[ 0 ];
			*fIt++ = quad[ 1 ];
			*fIt++ = quad[ 2 ];
			*fIt++ = quad[ 2 ];
			*fIt++ = quad[ 3 ];
			*fIt++ = quad[ 0 ];
		}
		quads += desc.quads.stride;
	}

    return faces;
}

} // anonymous namespace

RenderClothActor::RenderClothActor(SampleRenderer::Renderer& renderer, const PxCloth& cloth, const PxClothMeshDesc &desc, const PxVec2* uv, const PxReal capsuleScale)
    : mRenderer(renderer)
	, mCloth(cloth)
	, mNumFaces(0), mFaces(NULL)
	, mSpheres(0), mCapsules(0), mPlanes(0), mConvexes(0), mTriangles(0)
	, mNumSpheres(0), mNumCapsules(0), mNumPlanes(0), mNumConvexes(0), mNumTriangles(0)
    , mUV(NULL)
	, mCapsuleScale(capsuleScale)
    , mClothRenderShape(NULL)
	, mConvexMaterial(NULL)
	, mMeshActor(NULL)
	, mConvexActor(NULL)
{
	int numVerts = desc.points.count;

    mNumFaces = desc.triangles.count + 2*desc.quads.count;
    mFaces = createFacesFromMeshDesc(desc);

	const PxVec3* verts = reinterpret_cast<const PxVec3*>(desc.points.data);

    mUV = (PxReal*)SAMPLE_ALLOC(sizeof(PxReal)*numVerts*2);		
	if (uv)
		memcpy( mUV, uv, sizeof(PxReal) * 2 * numVerts);
	else
        createUVWithPlanarProjection(mUV, numVerts, verts);

	mClothVertices.resize(numVerts);
	mClothNormals.resize(numVerts);

	updateRenderShape();
}

RenderClothActor::~RenderClothActor() 
{
	SAMPLE_FREE( mUV );
    SAMPLE_FREE( mFaces );
	SAMPLE_FREE( mSpheres );
	SAMPLE_FREE( mCapsules );
	SAMPLE_FREE( mPlanes );
	SAMPLE_FREE( mConvexes );
	SAMPLE_FREE( mTriangles );
	
	freeCollisionRenderSpheres();
	freeCollisionRenderCapsules();

	delete mMeshActor;
	delete mConvexActor;
}

void RenderClothActor::setConvexMaterial(RenderMaterial* material)
{
	mConvexMaterial = material;
}

void RenderClothActor::freeCollisionRenderSpheres()
{
	for (PxU32 i=0; i < mSphereActors.size(); ++i)
		delete mSphereActors[i];

	mSphereActors.clear();
}

void RenderClothActor::freeCollisionRenderCapsules()
{
	for (PxU32 i=0; i < mCapsuleActors.size(); ++i)
		delete mCapsuleActors[i];

	mCapsuleActors.clear();
}

namespace
{
	void BuildNormals(const PxVec3* PX_RESTRICT vertices, PxU32 numVerts, const PxU16* PX_RESTRICT faces, PxU32 numFaces, PxVec3* PX_RESTRICT normals)
	{
		memset(normals, 0, sizeof(PxVec3)*numVerts);
		
		const PxU32 numIndices = numFaces*3;

		// accumulate area weighted face normals in each vertex
		for (PxU32 t=0; t < numIndices; t+=3)
		{
			PxU16 i = faces[t];
			PxU16 j = faces[t+1];
			PxU16 k = faces[t+2];

			PxVec3 e1 = vertices[j]-vertices[i];
			PxVec3 e2 = vertices[k]-vertices[i];

			PxVec3 n = e2.cross(e1);

			normals[i] += n;
			normals[j] += n;
			normals[k] += n;
		}

		// average
		for (PxU32 i=0; i < numVerts; ++i)
			normals[i].normalize();
	}
}


void RenderClothActor::updateRenderShape()
{
	PX_PROFILE_ZONE("RenderClothActor::updateRenderShape",0);
	
	int numVerts = mCloth.getNbParticles();

    PX_ASSERT(numVerts > 0);

    if(!mClothRenderShape)
    {
		PxCudaContextManager* ctxMgr = NULL;

#if defined(RENDERER_ENABLE_CUDA_INTEROP)
		PxGpuDispatcher* dispatcher = mCloth.getScene()->getTaskManager()->getGpuDispatcher();
		
		// contxt must be created in at least one valid interop mode
		if (dispatcher && (ctxMgr = dispatcher->getCudaContextManager()) && 
			ctxMgr->getInteropMode() != PxCudaInteropMode::D3D10_INTEROP &&
			ctxMgr->getInteropMode() != PxCudaInteropMode::D3D11_INTEROP)
		{		
			ctxMgr = NULL;
		}
#endif

        mClothRenderShape = new RendererClothShape(
            mRenderer,
            &mClothVertices[0],
            numVerts,
            &mClothNormals[0],
            mUV,
            &mFaces[0],
            mNumFaces, false, ctxMgr);

        setRenderShape(mClothRenderShape);
    }

	{
		PX_PROFILE_ZONE("RenderClothShape::update",0);
	
		bool needUpdate = true;

#if defined(RENDERER_ENABLE_CUDA_INTEROP)

		if (mCloth.getClothFlags()&PxClothFlag::eGPU && mClothRenderShape->isInteropEnabled())
		{
			PxClothParticleData* data = const_cast<PxCloth&>(mCloth).lockParticleData(PxDataAccessFlag::eDEVICE);
			{
				PX_PROFILE_ZONE("updateInterop",0);
				bool success = mClothRenderShape->update(reinterpret_cast<CUdeviceptr>(data->particles), numVerts);

				// if CUDA update succeeded then skip CPU update
				if (success)
					needUpdate = false;
			}
			data->unlock();
		}
#endif // RENDERER_ENABLE_CUDA_INTEROP

		if (needUpdate)
		{
			bool result;	
			result = getVertsFromCloth(&mClothVertices[0], mCloth);
			PX_UNUSED(result);
			PX_ASSERT(result == true);

			{
				// update render normals
				PX_PROFILE_ZONE("BuildSmoothNormals",0);
				BuildNormals(&mClothVertices[0], mClothVertices.size(), mFaces, mNumFaces, &mClothNormals[0]);
			}

			mClothRenderShape->update(&mClothVertices[0], numVerts, &mClothNormals[0]);
		}
	}

	setTransform(mCloth.getGlobalPose());
}

namespace
{
	struct ConvexMeshBuilder
	{
		ConvexMeshBuilder(const PxVec4* planes)
			: mPlanes(planes)
		{}

		void operator()(PxU32 mask, float scale=1.0f);

		const PxVec4* mPlanes;
		shdfnd::Array<PxVec3> mVertices;
		shdfnd::Array<PxU16> mIndices;
	};

	/*
	void test()
	{
		int data[4*32];
		float planes[4*32];

		for(PxU32 numPlanes = 1; numPlanes<=32; ++numPlanes)
		{
			int seed = 0;

			const PxU32 planeMask = (PxU64(1) << numPlanes) - 1;
			for(PxU32 i=0; i<100000; ++i)
			{
				srand(seed);

				for(PxU32 j=0; j<4*numPlanes; ++j)
					planes[j] = float(data[j] = rand()) / RAND_MAX * 2.0f - 1.0f;

				ConvexMeshBuilder builder(reinterpret_cast<PxVec4*>(planes));
				builder(planeMask, 0.0f);

				seed = data[numPlanes*4-1];
			}
		}
	}
	*/
}

void RenderClothActor::update(float deltaTime)
{
	PX_PROFILE_ZONE("RenderClothActor::update",0);

	updateRenderShape();

	// update collision shapes
	PxU32 numSpheres = mCloth.getNbCollisionSpheres();
	PxU32 numCapsules = mCloth.getNbCollisionCapsules();
	PxU32 numPlanes = mCloth.getNbCollisionPlanes();
	PxU32 numConvexes = mCloth.getNbCollisionConvexes();
	PxU32 numTriangles = mCloth.getNbCollisionTriangles();

	if (numSpheres == 0 && mNumSpheres == 0 &&
        numTriangles == 0 && mNumTriangles == 0 &&
		numConvexes == 0 && mNumConvexes == 0)
		return;

	if(numSpheres != mNumSpheres)
	{
		SAMPLE_FREE(mSpheres);
		mSpheres = (PxClothCollisionSphere*)SAMPLE_ALLOC(sizeof(PxClothCollisionSphere) * (mNumSpheres = numSpheres));
	}

	if(numCapsules != mNumCapsules)
	{
		SAMPLE_FREE(mCapsules);
		mCapsules = (PxU32*)SAMPLE_ALLOC(sizeof(PxU32) * 2 * (mNumCapsules = numCapsules));
	}

	if(numPlanes != mNumPlanes)
	{
		SAMPLE_FREE(mPlanes);
		mPlanes = (PxClothCollisionPlane*)SAMPLE_ALLOC(sizeof(PxClothCollisionPlane) * (mNumPlanes = numPlanes));
	}

	if(numConvexes != mNumConvexes)
	{
		SAMPLE_FREE(mConvexes);
		mConvexes = (PxU32*)SAMPLE_ALLOC(sizeof(PxU32) * (mNumConvexes = numConvexes));
	}

	if(numTriangles != mNumTriangles)
	{
		SAMPLE_FREE(mTriangles);
		mTriangles = (PxClothCollisionTriangle*)SAMPLE_ALLOC(sizeof(PxClothCollisionTriangle) * (mNumTriangles = numTriangles));
		mMeshIndices.resize(0); mMeshIndices.reserve(mNumTriangles*3);
		for(PxU32 i=0; i<mNumTriangles*3; ++i)
			mMeshIndices.pushBack(PxU16(i));
	}

	{
		PX_PROFILE_ZONE("mCloth.getCollisionData",0);
		mCloth.getCollisionData(mSpheres, mCapsules, mPlanes, mConvexes, mTriangles);
	}

	PxTransform clothPose = mCloth.getGlobalPose();

	// see if we need to recreate the collision shapes (count has changed)
	if (numSpheres != mSphereActors.size())
	{
		freeCollisionRenderSpheres();

		// create sphere actors (we reuse the RenderCapsuleActor type)
		for (PxU32 i=0; i < numSpheres; i++)
		{
			RenderSphereActor* sphere = SAMPLE_NEW(RenderSphereActor)(mClothRenderShape->getRenderer(), 1.0f);
			mSphereActors.pushBack(sphere);
		}
	}

	if (numCapsules != mCapsuleActors.size())
	{
		freeCollisionRenderCapsules();

		// create capsule actors
		for (PxU32 i=0; i < numCapsules; i++)
		{
			RenderCapsuleActor* capsule = SAMPLE_NEW(RenderCapsuleActor)(mClothRenderShape->getRenderer(), 1.0f, 1.0f);
			mCapsuleActors.pushBack(capsule);
		}
	}

	
	{
		PX_PROFILE_ZONE("updateRenderSpheres",0);

		// update all spheres
		for (PxU32 i=0; i < numSpheres; ++i)
		{
			float r = mSpheres[i].radius*mCapsuleScale;

			mSphereActors[i]->setRendering(true);
			mSphereActors[i]->setTransform(PxTransform(clothPose.transform(mSpheres[i].pos)));
			mSphereActors[i]->setMeshScale(PxMeshScale(PxVec3(r, r, r), PxQuat(PxIdentity)));
		}
	}


	{
		PX_PROFILE_ZONE("updateRenderCapsules",0);

		// capsule needs to be flipped to match PxTransformFromSegment
		PxTransform flip(PxVec3(0.0f), PxQuat(-PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f)));

		// update all capsules
		for (PxU32 i=0; i < numCapsules; ++i)
		{
			PxU32 i0 = mCapsules[i*2];
			PxU32 i1 = mCapsules[i*2+1];

			PxClothCollisionSphere& sphere0 = mSpheres[i0];
			PxClothCollisionSphere& sphere1 = mSpheres[i1];
			
			// disable individual rendering for spheres belonging to a capsule
			mSphereActors[i0]->setRendering(false);
			mSphereActors[i1]->setRendering(false);

			PxVec3 p0 = clothPose.transform(sphere0.pos);
			PxVec3 p1 = clothPose.transform(sphere1.pos);

			mCapsuleActors[i]->setDimensions((p1-p0).magnitude()*0.5f, mCapsuleScale*sphere0.radius, mCapsuleScale*sphere1.radius);
			mCapsuleActors[i]->setTransform(PxTransformFromSegment(p0, p1)*flip);		
		}
	}

	// update all triangles
	SAMPLE_FREE(mMeshActor);
	if(mNumTriangles)
	{
		mMeshActor = SAMPLE_NEW(RenderMeshActor)(mRenderer, reinterpret_cast<const PxVec3*>(
			mTriangles), mNumTriangles*3, 0, 0, mMeshIndices.begin(), NULL, mNumTriangles, true);
		mMeshActor->setTransform(clothPose);
	}

	SAMPLE_FREE(mConvexActor);
	if(mNumConvexes)
	{
		ConvexMeshBuilder builder(reinterpret_cast<const PxVec4*>(mPlanes));
		for(PxU32 i=0; i<mNumConvexes; ++i)
			builder(mConvexes[i], mCloth.getWorldBounds().getExtents().maxElement());
		mConvexVertices = builder.mVertices;
		mConvexIndices = builder.mIndices;
		if(!mConvexIndices.empty())
		{
			mConvexActor = SAMPLE_NEW(RenderMeshActor)(mRenderer, mConvexVertices.begin(), 
				mConvexVertices.size(), 0, 0, mConvexIndices.begin(), NULL, mConvexIndices.size()/3, true);
			mConvexActor->setTransform(clothPose);
		}
	}

}

void RenderClothActor::render(SampleRenderer::Renderer& renderer, RenderMaterial* material, bool wireFrame)
{
	RenderBaseActor::render(renderer, material, wireFrame);

	// render collision shapes

	for (PxU32 i=0; i < mSphereActors.size(); ++i)
		mSphereActors[i]->render(renderer, material, wireFrame);

	for (PxU32 i=0; i < mCapsuleActors.size(); ++i)
		mCapsuleActors[i]->render(renderer, material, wireFrame);

	if(mMeshActor)
		mMeshActor->render(renderer, material, wireFrame);

	if(mConvexActor)
		mConvexActor->render(renderer, mConvexMaterial ? mConvexMaterial : material, wireFrame);
}

namespace
{
	PxReal det(PxVec4 v0, PxVec4 v1, PxVec4 v2, PxVec4 v3)
	{
		const PxVec3& d0 = reinterpret_cast<const PxVec3&>(v0);
		const PxVec3& d1 = reinterpret_cast<const PxVec3&>(v1);
		const PxVec3& d2 = reinterpret_cast<const PxVec3&>(v2);
		const PxVec3& d3 = reinterpret_cast<const PxVec3&>(v3);

		return v0.w * d1.cross(d2).dot(d3)
			- v1.w * d0.cross(d2).dot(d3)
			+ v2.w * d0.cross(d1).dot(d3)
			- v3.w * d0.cross(d1).dot(d2);
	}

	PxVec3 intersect(PxVec4 p0, PxVec4 p1, PxVec4 p2)
	{
		const PxVec3& d0 = reinterpret_cast<const PxVec3&>(p0);
		const PxVec3& d1 = reinterpret_cast<const PxVec3&>(p1);
		const PxVec3& d2 = reinterpret_cast<const PxVec3&>(p2);

		return (p0.w * d1.cross(d2) 
			  + p1.w * d2.cross(d0) 
			  + p2.w * d0.cross(d1))
			  / d0.dot(d2.cross(d1));
	}

	const PxU16 sInvalid = PxU16(-1);

	// restriction: only supports a single patch per vertex.
	struct HalfedgeMesh
	{
		struct Halfedge
		{
			Halfedge(PxU16 vertex = sInvalid, PxU16 face = sInvalid, 
				PxU16 next = sInvalid, PxU16 prev = sInvalid)
				: mVertex(vertex), mFace(face), mNext(next), mPrev(prev)
			{}

			PxU16 mVertex; // to
			PxU16 mFace; // left
			PxU16 mNext; // ccw
			PxU16 mPrev; // cw
		};

		HalfedgeMesh() : mNumTriangles(0) {}

		PxU16 findHalfedge(PxU16 v0, PxU16 v1)
		{
			PxU16 h = mVertices[v0], start = h;
			while(h != sInvalid && mHalfedges[h].mVertex != v1)
			{
				h = mHalfedges[h ^ 1].mNext;
				if(h == start) 
					return sInvalid;
			}
			return h;
		}

		void connect(PxU16 h0, PxU16 h1)
		{
			mHalfedges[h0].mNext = h1;
			mHalfedges[h1].mPrev = h0;
		}

		void addTriangle(PxU16 v0, PxU16 v1, PxU16 v2)
		{
			// add new vertices
			PxU16 n = PxMax(v0, PxMax(v1, v2))+1;
			if(mVertices.size() < n)
				mVertices.resize(n, sInvalid);

			// collect halfedges, prev and next of triangle
			PxU16 verts[] = { v0, v1, v2 };
			PxU16 handles[3], prev[3], next[3];
			for(PxU16 i=0; i<3; ++i)
			{
				PxU16 j = (i+1)%3;
				PxU16 h = findHalfedge(verts[i], verts[j]);
				if(h == sInvalid)
				{
					// add new edge
					h = mHalfedges.size();
					mHalfedges.pushBack(Halfedge(verts[j]));
					mHalfedges.pushBack(Halfedge(verts[i]));
				}
				handles[i] = h;
				prev[i] = mHalfedges[h].mPrev;
				next[i] = mHalfedges[h].mNext;
			}

			// patch connectivity
			for(PxU16 i=0; i<3; ++i)
			{
				PxU16 j = (i+1)%3;

				mHalfedges[handles[i]].mFace = mFaces.size();

				// connect prev and next
				connect(handles[i], handles[j]);

				if(next[j] == sInvalid) // new next edge, connect opposite
					connect(handles[j]^1, next[i]!=sInvalid ? next[i] : handles[i]^1);

				if(prev[i] == sInvalid) // new prev edge, connect opposite
					connect(prev[j]!=sInvalid ? prev[j] : handles[j]^1, handles[i]^1);

				// prev is boundary, update middle vertex
				if(mHalfedges[handles[i]^1].mFace == sInvalid)
					mVertices[verts[j]] = handles[i]^1;
			}

			PX_ASSERT(mNumTriangles < 0xffff);
			mFaces.pushBack(handles[2]);
			++mNumTriangles;
		}

		PxU16 removeTriangle(PxU16 f)
		{
			PxU16 result = sInvalid;

			for(PxU16 i=0, h = mFaces[f]; i<3; ++i)
			{
				PxU16 v0 = mHalfedges[h^1].mVertex;
				PxU16 v1 = mHalfedges[h].mVertex;

				mHalfedges[h].mFace = sInvalid;

				if(mHalfedges[h^1].mFace == sInvalid) // was boundary edge, remove
				{
					PxU16 v0Prev = mHalfedges[h  ].mPrev;
					PxU16 v0Next = mHalfedges[h^1].mNext;
					PxU16 v1Prev = mHalfedges[h^1].mPrev;
					PxU16 v1Next = mHalfedges[h  ].mNext;

					// update halfedge connectivity
					connect(v0Prev, v0Next);
					connect(v1Prev, v1Next);

					// update vertex boundary or delete
					mVertices[v0] = (v0Prev^1) == v0Next ? sInvalid : v0Next;
					mVertices[v1] = (v1Prev^1) == v1Next ? sInvalid : v1Next;
				} 
				else 
				{
					mVertices[v0] = h; // update vertex boundary
					result = v1;
				}

				h = mHalfedges[h].mNext;
			}

			mFaces[f] = sInvalid;
			--mNumTriangles;

			return result;
		}

		// true if vertex v is in front of face f
		bool visible(PxU16 v, PxU16 f)
		{
			PxU16 h = mFaces[f];
			if(h == sInvalid)
				return false;

			PxU16 v0 = mHalfedges[h].mVertex;
			h = mHalfedges[h].mNext;
			PxU16 v1 = mHalfedges[h].mVertex;
			h = mHalfedges[h].mNext;
			PxU16 v2 = mHalfedges[h].mVertex;
			h = mHalfedges[h].mNext;

			return det(mPoints[v], mPoints[v0], mPoints[v1], mPoints[v2]) < -1e-5f;
		}

		/*
		void print() const
		{
			for(PxU32 i=0; i<mFaces.size(); ++i)
			{
				shdfnd::printFormatted("f%u: ", i);
				PxU16 h = mFaces[i];
				if(h == sInvalid)
				{
					shdfnd::printFormatted("deleted\n");
					continue;
				}

				for(int j=0; j<3; ++j)
				{
					shdfnd::printFormatted("h%u -> v%u -> ", PxU32(h), PxU32(mHalfedges[h].mVertex));
					h = mHalfedges[h].mNext;
				}

				shdfnd::printFormatted("\n");
			}

			for(PxU32 i=0; i<mVertices.size(); ++i)
			{
				shdfnd::printFormatted("v%u: ", i);
				PxU16 h = mVertices[i];
				if(h == sInvalid)
				{
					shdfnd::printFormatted("deleted\n");
					continue;
				}
				
				PxU16 start = h;
				do {
					shdfnd::printFormatted("h%u -> v%u, ", PxU32(h), PxU32(mHalfedges[h].mVertex));
					h = mHalfedges[h^1].mNext;
				} while (h != start);

				shdfnd::printFormatted("\n");
			}

			for(PxU32 i=0; i<mHalfedges.size(); ++i)
			{
				shdfnd::printFormatted("h%u: v%u, ", i, PxU32(mHalfedges[i].mVertex));

				if(mHalfedges[i].mFace == sInvalid)
					shdfnd::printFormatted("boundary, ");
				else
					shdfnd::printFormatted("f%u, ", PxU32(mHalfedges[i].mFace));

				shdfnd::printFormatted("p%u, n%u\n", PxU32(mHalfedges[i].mPrev), PxU32(mHalfedges[i].mNext));
			}
		}
		*/

		shdfnd::Array<Halfedge> mHalfedges;
		shdfnd::Array<PxU16> mVertices; // vertex -> (boundary) halfedge
		shdfnd::Array<PxU16> mFaces; // face -> halfedge
		shdfnd::Array<PxVec4> mPoints;
		PxU16 mNumTriangles;
	};
}

void ConvexMeshBuilder::operator()(PxU32 planeMask, float scale)
{
	PxU16 numPlanes = shdfnd::bitCount(planeMask);

	if (numPlanes == 1)
	{
		PxTransform t = PxTransformFromPlaneEquation(reinterpret_cast<const PxPlane&>(mPlanes[Ps::lowestSetBit(planeMask)]));

		if (!t.isValid())
			return;

		const PxU16 indices[] = { 0, 1, 2, 0, 2, 3 };
		const PxVec3 vertices[] = { 
			PxVec3(0.0f,  scale,  scale), 
			PxVec3(0.0f, -scale,  scale),
			PxVec3(0.0f, -scale, -scale),			
			PxVec3(0.0f,  scale, -scale) };

		PxU32 baseIndex = mVertices.size();

		for (PxU32 i=0; i < 4; ++i)
			mVertices.pushBack(t.transform(vertices[i]));

		for (PxU32 i=0; i < 6; ++i)
			mIndices.pushBack(indices[i] + baseIndex);

		return;
	}

	if(numPlanes < 4)
		return; // todo: handle degenerate cases

	HalfedgeMesh mesh;

	// gather points (planes, that is)
	mesh.mPoints.reserve(numPlanes);
	for(; planeMask; planeMask &= planeMask-1)
		mesh.mPoints.pushBack(mPlanes[shdfnd::lowestSetBit(planeMask)]);

	// initialize to tetrahedron
	mesh.addTriangle(0, 1, 2);
	mesh.addTriangle(0, 3, 1);
	mesh.addTriangle(1, 3, 2);
	mesh.addTriangle(2, 3, 0);

	// flip if inside-out
	if(mesh.visible(3, 0))
		shdfnd::swap(mesh.mPoints[0], mesh.mPoints[1]);

	// iterate through remaining points
	for(PxU16 i=4; i<mesh.mPoints.size(); ++i)
	{
		// remove any visible triangle
		PxU16 v0 = sInvalid;
		for(PxU16 j=0; j<mesh.mFaces.size(); ++j)
		{
			if(mesh.visible(i, j))
				v0 = PxMin(v0, mesh.removeTriangle(j));
		}

		if(v0 == sInvalid)
			continue; // no triangle removed

		if(!mesh.mNumTriangles)
			return; // empty mesh

		// find non-deleted boundary vertex
		for(PxU16 h=0; mesh.mVertices[v0] == sInvalid; h+=2)
		{
			if ((mesh.mHalfedges[h  ].mFace == sInvalid) ^ 
				(mesh.mHalfedges[h+1].mFace == sInvalid))
			{
				v0 = mesh.mHalfedges[h].mVertex;
			}
		}

		// tesselate hole
		PxU16 start = v0;
		do {
			PxU16 h = mesh.mVertices[v0];
			PxU16 v1 = mesh.mHalfedges[h].mVertex;
			mesh.addTriangle(v0, v1, i);
			v0 = v1;
		} while(v0 != start);
	}

	// convert triangles to vertices (intersection of 3 planes)
	shdfnd::Array<PxU32> face2Vertex(mesh.mFaces.size(), sInvalid);
	for(PxU32 i=0; i<mesh.mFaces.size(); ++i)
	{
		PxU16 h = mesh.mFaces[i];
		if(h == sInvalid)
			continue;

		PxU16 v0 = mesh.mHalfedges[h].mVertex;
		h = mesh.mHalfedges[h].mNext;
		PxU16 v1 = mesh.mHalfedges[h].mVertex;
		h = mesh.mHalfedges[h].mNext;
		PxU16 v2 = mesh.mHalfedges[h].mVertex;

		face2Vertex[i] = mVertices.size();
		mVertices.pushBack(intersect(mesh.mPoints[v0], mesh.mPoints[v1], mesh.mPoints[v2]));
	}

	// convert vertices to polygons (face one-ring)
	for(PxU32 i=0; i<mesh.mVertices.size(); ++i)
	{
		PxU16 h = mesh.mVertices[i];
		if(h == sInvalid)
			continue;

		PxU16 v0 = face2Vertex[mesh.mHalfedges[h].mFace];
		h = mesh.mHalfedges[h].mPrev^1;
		PxU16 v1 = face2Vertex[mesh.mHalfedges[h].mFace];

		while(true)
		{
			h = mesh.mHalfedges[h].mPrev^1;
			PxU16 v2 = face2Vertex[mesh.mHalfedges[h].mFace];

			if(v0 == v2) 
				break;

			PxVec3 e0 =  mVertices[v0] -  mVertices[v2];
			PxVec3 e1 =  mVertices[v1] -  mVertices[v2];
			if(e0.cross(e1).magnitudeSquared() < 1e-10f)
				continue;

			mIndices.pushBack(v0);
			mIndices.pushBack(v2);
			mIndices.pushBack(v1);

			v1 = v2; 
		}

	}
}

#endif // PX_USE_CLOTH_API