aboutsummaryrefslogtreecommitdiff
path: root/examples/UnityExample/Assets/Scripts/CubeFamily.cs
blob: 1139078bdc58c139117d9cee9f2c2a4474a9bf11 (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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;


public class CubeFamily : MonoBehaviour
{
    public void Initialize(CubeAsset asset)
    {
        // Blast asset creation
        _cubeAsset = asset;

        NvBlastAssetDesc desc = _cubeAsset.solverAssetDesc;
        _blastAsset = new NvBlastAsset(desc);
//        Debug.Log(_blastAsset.leafChunkCount);

        // Actual Cubes
        var cubePrefab = Resources.Load<GameObject>("CubePrefab");
        _cubes = new GameObject[desc.chunkCount];
        for (int i = 0; i < desc.chunkCount; ++i)
        {
            GameObject cube = GameObject.Instantiate<GameObject>(cubePrefab);
            cube.transform.parent = transform;
            cube.transform.localScale = _cubeAsset.chunks[i].extents;
            cube.transform.localPosition = _cubeAsset.chunks[i].position;
            cube.transform.localRotation = Quaternion.identity;
            cube.SetActive(false);
            Color color = Color.HSVToRGB(UnityEngine.Random.Range(0f, 1f), 0.42f, 1.0f);
            cube.GetComponent<Renderer>().material.color = color;
            _cubes[i] = cube;
        }

        // First actor
        _blastFamily = new NvBlastFamily(_blastAsset);

        NvBlastActorDesc actorDesc = new NvBlastActorDesc();
        actorDesc.uniformInitialBondHealth = 1.0f;
        actorDesc.uniformInitialLowerSupportChunkHealth = 1.0f;
        var actor = new NvBlastActor(_blastFamily, actorDesc);
//        Debug.Log(actor.visibleChunkCount);

        OnActorCreated(actor, Vector3.zero, Quaternion.identity);

        // Reserved buffers
        _fractureBuffers = new NvBlastFractureBuffers();
        _fractureBuffers.chunkFractures = Marshal.AllocHGlobal((int)desc.chunkCount * Marshal.SizeOf(typeof(NvBlastChunkFractureData)));
        _fractureBuffers.bondFractures = Marshal.AllocHGlobal((int)desc.bondCount * Marshal.SizeOf(typeof(NvBlastBondFractureData)));
        _leafChunkCount = (uint)_blastAsset.leafChunkCount;
        _newActorsBuffer = Marshal.AllocHGlobal((int)_leafChunkCount * Marshal.SizeOf(typeof(IntPtr)));
    }

    private void OnActorCreated(NvBlastActor actor, Vector3 localPosition, Quaternion localRotation)
    {
        var rigidBodyGO = new GameObject("RigidActor");
        rigidBodyGO.transform.SetParent(this.transform, false);
        var rigidbody = rigidBodyGO.AddComponent<Rigidbody>();
        rigidbody.transform.localPosition = localPosition;
        rigidbody.transform.localRotation = localRotation;

        // chunks
        var chunkIndices = actor.visibleChunkIndices;
        foreach (var chunkIndex in chunkIndices)
        {
            var chunkCube = _cubes[chunkIndex];
            chunkCube.transform.SetParent(rigidbody.transform, false);
            chunkCube.SetActive(true);
        }

        // search for static chunks
        var graphNodeIndices = actor.graphNodeIndices;
        var chunkGraph = _blastAsset.chunkGraph;
        foreach(var node in graphNodeIndices)
        {
            var chunkIndex = Marshal.ReadInt32(chunkGraph.chunkIndices, Marshal.SizeOf(typeof(UInt32)) * (int)node);
            var chunkCube = _cubeAsset.chunks[chunkIndex];
            if(chunkCube.isStatic)
            {
                rigidbody.isKinematic = true;
                break;
            }
        }

        actor.userData = rigidbody;
        _actors.Add(rigidbody, actor);
    }

    private void OnActorDestroyed(NvBlastActor actor)
    {
        var chunkIndices = actor.visibleChunkIndices;
        foreach (var chunkIndex in chunkIndices)
        {
            var chunkCube = _cubes[chunkIndex];
            chunkCube.transform.SetParent(transform, false);
            chunkCube.SetActive(false);
        }

        var rigidbody = (actor.userData as Rigidbody);
        _actors.Remove(rigidbody);
        Destroy(rigidbody.gameObject);
        actor.userData = null;
    }

    public void ApplyRadialDamage(Vector3 position, float minRadius, float maxRadius, float compressive)
    {
        var hits = Physics.OverlapSphere(position, maxRadius);
        foreach (var hit in hits)
        {
            var rb = hit.GetComponentInParent<Rigidbody>();
            if (rb != null)
            {
                ApplyRadialDamage(rb, position, minRadius, maxRadius, compressive);
            }
        }
    }

    public bool ApplyRadialDamage(Rigidbody rb, Vector3 position, float minRadius, float maxRadius, float compressive)
    {
        if (_actors.ContainsKey(rb))
        {
            Vector3 localPosition = rb.transform.InverseTransformPoint(position);
            ApplyRadialDamage(_actors[rb], localPosition, minRadius, maxRadius, compressive);
            return true;
        }
        return false;
    }

    private void ApplyRadialDamage( NvBlastActor actor, Vector3 localPosition, float minRadius, float maxRadius, float compressive )
    {
        _fractureBuffers.chunkFractureCount = _cubeAsset.solverAssetDesc.chunkCount;
        _fractureBuffers.bondFractureCount = _cubeAsset.solverAssetDesc.bondCount;

        NvBlastExtRadialDamageDesc desc = new NvBlastExtRadialDamageDesc();
        desc.minRadius = minRadius;
        desc.maxRadius = maxRadius;
        desc.damage = compressive;
        desc.p0 = localPosition.x;
        desc.p1 = localPosition.y;
        desc.p2 = localPosition.z;

		IntPtr dam = Marshal.AllocHGlobal( Marshal.SizeOf( typeof(NvBlastExtRadialDamageDesc) ) );
		Marshal.StructureToPtr( desc, dam, false );

		var damP = new NvBlastDamageProgram() {
			graphShaderFunction = NvBlastExtShadersWrapper.NvBlastExtFalloffGraphShader,
			subgraphShaderFunction = NvBlastExtShadersWrapper.NvBlastExtFalloffSubgraphShader
			};
		var programParams = new NvBlastExtProgramParams() {
			damageDescBuffer = dam,
			material = IntPtr.Zero,
			accelerator = IntPtr.Zero
		};

		actor.GenerateFracture( _fractureBuffers, damP, programParams );
		actor.ApplyFracture( _fractureBuffers );
		if ( _fractureBuffers.bondFractureCount + _fractureBuffers.chunkFractureCount > 0 )
		{
			Split( actor );
		}

		Marshal.FreeHGlobal(dam);
    }

    private void Split( NvBlastActor actor )
    {
        NvBlastActorSplitEvent split = new NvBlastActorSplitEvent();
        split.newActors = _newActorsBuffer;
        var count = actor.Split(split, _leafChunkCount);

        Vector3 localPosition = Vector3.zero;
        Quaternion localRotation = Quaternion.identity;

        if (split.deletedActor != IntPtr.Zero)
        {
            if (actor.userData != null)
            {
                var parentRigidbody = (actor.userData as Rigidbody);
                localPosition = parentRigidbody.transform.localPosition;
                localRotation = parentRigidbody.transform.localRotation;
            }
            OnActorDestroyed(actor);
        }
        for (int i = 0; i < count; i++)
        {
            int elementSize = Marshal.SizeOf(typeof(IntPtr));
            var ptr = Marshal.ReadIntPtr(split.newActors, elementSize * i);
            OnActorCreated(new NvBlastActor(_blastFamily, ptr), localPosition, localRotation);
        }
    }

    private void OnDestroy()
    {
        if (_fractureBuffers != null)
        {
            Marshal.FreeHGlobal(_fractureBuffers.chunkFractures);
            Marshal.FreeHGlobal(_fractureBuffers.bondFractures);
            _fractureBuffers = null;
        }

        if (_newActorsBuffer != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(_newActorsBuffer);
        }

        _actors.Clear();
        _blastFamily = null;
        _blastAsset = null;
    }

    private CubeAsset _cubeAsset;
    private NvBlastAsset _blastAsset;
    private NvBlastFamily _blastFamily;
    private Dictionary<Rigidbody, NvBlastActor> _actors = new Dictionary<Rigidbody, NvBlastActor>();
    private GameObject[] _cubes;
    private NvBlastFractureBuffers _fractureBuffers;
    private IntPtr _newActorsBuffer;
    private uint _leafChunkCount;
}