Example #1
0
        public Entity CreateBody(RenderMesh displayMesh, float3 position, quaternion orientation,
                                 BlobAssetReference <Unity.Physics.Collider> collider,
                                 float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic)
        {
            ComponentType[] componentTypes = new ComponentType[isDynamic ? 9 : 6];

            componentTypes[0] = typeof(RenderMesh);
            componentTypes[1] = typeof(TranslationProxy);
            componentTypes[2] = typeof(RotationProxy);
            componentTypes[3] = typeof(PhysicsCollider);
            componentTypes[4] = typeof(Translation);
            componentTypes[5] = typeof(Rotation);
            if (isDynamic)
            {
                componentTypes[6] = typeof(PhysicsVelocity);
                componentTypes[7] = typeof(PhysicsMass);
                componentTypes[8] = typeof(PhysicsDamping);
            }
            EntityManager entityManager = EntityManager;

            Entity entity = entityManager.CreateEntity(componentTypes);

            entityManager.SetName(entity, "randomSphere");
            entityManager.SetSharedComponentData(entity, displayMesh);

            entityManager.AddComponentData(entity, new LocalToWorld {
            });
            entityManager.SetComponentData(entity, new Translation {
                Value = position
            });
            entityManager.SetComponentData(entity, new Rotation {
                Value = orientation
            });
            entityManager.SetComponentData(entity, new PhysicsCollider {
                Value = collider
            });
            if (isDynamic)
            {
                MassProperties massProperties = collider.Value.MassProperties;
                entityManager.SetComponentData(entity, PhysicsMass.CreateDynamic(
                                                   massProperties, mass));
                float3 angularVelocityLocal = math.mul(
                    math.inverse(massProperties.MassDistribution.Transform.rot),
                    angularVelocity);
                entityManager.SetComponentData(entity, new PhysicsVelocity()
                {
                    Linear  = linearVelocity,
                    Angular = angularVelocityLocal
                });
                entityManager.SetComponentData(entity, new PhysicsDamping()
                {
                    Linear  = 0.01f,
                    Angular = 0.05f
                });
            }

            return(entity);
        }
Example #2
0
    protected unsafe override void Start()
    {
        float3 gravity = float3.zero;

        base.init(gravity);

        // Enable the joint viewer
        SetDebugDisplay(new Unity.Physics.Authoring.PhysicsDebugDisplayData
        {
            DrawJoints = 1,
        });

        // static body
        Entity staticEntity;
        {
            BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.BoxCollider.Create(new BoxGeometry
            {
                Center      = float3.zero,
                Orientation = quaternion.identity,
                Size        = new float3(1.0f),
                BevelRadius = 0.01f
            });
            staticEntity = CreateStaticBody(float3.zero, quaternion.identity, collider);
        }

        // dynamic body
        Entity dynamicEntity;
        {
            BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-0.5f, 0, 0),
                Vertex1 = new float3(0.5f, 0, 0),
                Radius  = 0.05f
            });
            float3 angularVelocity = new float3(0, 1.0f, 0);
            dynamicEntity = CreateDynamicBody(new float3(2, 0, 0), quaternion.identity, collider, float3.zero, angularVelocity, 1.0f);
        }

        // 1D angular limit
        //{
        //    float3 pivotA = new float3(-0.5f, 0, 0);
        //    float3 pivotB = GetBodyTransform(staticEntity).Inverse().TransformPoint(GetBodyTransform(dynamicEntity).TransformPoint(pivotA));

        //    BlobAssetReference<JointData> jointData;
        //    using (var allocator = new BlobAllocator(-1))
        //    {
        //        Constraint angLimit = Constraint.Twist(0, -(float)math.PI / 4.0f, (float)math.PI / 4.0f);
        //        ref JointData data = ref allocator.ConstructRoot<JointData>();
        //        data.Init(
        //            new MTransform(float3x3.identity, pivotA),
        //            new MTransform(float3x3.identity, pivotB),
        //            &angLimit, 1);
        //        jointData = allocator.CreateBlobAssetReference<JointData>(Allocator.Persistent);
        //    }

        //    CreateJoint(jointData, dynamicEntity, staticEntity);
        //}
    }
Example #3
0
    // Update is called once per frame
    void Update()
    {
        if (!musicPlayer.isPlaying)
        {
            return;
        }

        int sampleValue = Mathf.ClosestPowerOfTwo((int)Mathf.Pow(SampleCount, 2f));

        if (sampleValue != lastSampleCount)
        {
            ShutdownVisuals();
            lastSampleCount = sampleValue;
            lastSampleData  = new float[lastSampleCount];
            SetUpVisuals(sampleValue * musicClip.channels, sampleValue);
        }

#if DOTS
        // if(!SampleData.IsCreated)
        // {
        //     Debug.Log("SampleData is Null");
        //     return;
        // }

        int arrayLength = SampleData.Value.sampleArray.Length;

        if (arrayLength != lastSampleCount * musicClip.channels)
        {
            //TODO: Resize the Blob array
            arrayLength = lastSampleCount * musicClip.channels;

            //Dispose of the old blob array
            SampleData.Dispose();

            using (BlobBuilder blobBuilder = new BlobBuilder(Allocator.Temp))
            {
                ref MusicDataBlobAsset musicDataBlobAsset = ref blobBuilder.ConstructRoot <MusicDataBlobAsset>();

                BlobBuilderArray <MusicSample> musicDataArray = blobBuilder.Allocate(ref musicDataBlobAsset.sampleArray, arrayLength);

                //Setup array data
                for (int i = 0; i < arrayLength; i++)
                {
                    musicDataArray[i] = new MusicSample {
                        Value = 0
                    };
                }

                SampleData = blobBuilder.CreateBlobAssetReference <MusicDataBlobAsset>(Allocator.Persistent);

                for (int i = 0; i < entityVisualizers.Length; i++)
                {
                    var viz = entityManager.GetComponentData <VisualizerData>(entityVisualizers[i]);
                    viz.MusicData = SampleData;
                    entityManager.SetComponentData <VisualizerData>(entityVisualizers[i], viz);
                }
            }
        }
Example #4
0
    private void createFlockAgent()
    {
        EntityArchetype agent  = em.CreateArchetype(typeof(Translation), typeof(RenderMesh), typeof(LocalToWorld), typeof(RenderBounds), typeof(PhysicsCollider), typeof(Rotation), typeof(PhysicsVelocity));
        Entity          eAgent = em.CreateEntity(agent);

        em.SetComponentData(eAgent, new Translation
        {
            Value = new float3(Random.Range(0, 50), 0, Random.Range(0, 50))
        });
        em.SetComponentData(eAgent, new Rotation()
        {
            Value = quaternion.identity
        });
        em.SetComponentData(eAgent, new PhysicsCollider()
        {
        });
        em.SetSharedComponentData(eAgent, new RenderMesh
        {
            mesh     = playerMesh,
            material = playerMat
        });
        em.SetSharedComponentData(eAgent, new BatchFilter
        {
            Value = 1
        });
        BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.BoxCollider.Create(
            new BoxGeometry
        {
            Size        = new float3(1),
            Orientation = quaternion.identity
        },
            new CollisionFilter
        {
            BelongsTo        = 1u << 0,
                CollidesWith = 1u << 2,
                GroupIndex   = 0
        }
            );

        em.SetComponentData(eAgent, new PhysicsCollider
        {
            Value = Unity.Physics.SphereCollider.Create(
                new SphereGeometry()
            {
                Center = float3.zero,
                Radius = 2f
                         //Size = new float3(1),
                         //Orientation = quaternion.identity
            },
                new CollisionFilter
            {
                BelongsTo        = 1u << 0,
                    CollidesWith = 1u << 2,
                    GroupIndex   = 0
            }
                )
        });
    }
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        var rigComponent = GetComponent <RigComponent>();

        if (rigComponent != null)
        {
            var buffer = dstManager.AddBuffer <PhysicsColliderFollowEntityData>(entity);
            GetData(rigComponent, out Transform[] children, out var shapes);
            //    children = new Transform[0];
            if (children.Length > 1)
            {
                int numberOfValidShapes = GetNumberOfValidShapes(shapes);
                NativeList <CompoundCollider.ColliderBlobInstance> blobs = new NativeList <CompoundCollider.ColliderBlobInstance>(Allocator.TempJob);
                for (int i = 0; i < children.Length; i++)
                {
                    if (shapes[i] != null && shapes[i].enabled)
                    {
                        var shapeExt = children[i].gameObject.GetComponent <PhysicsMaterialsExtensionComponent>();

                        BlobAssetReference <Unity.Physics.Collider> collider = GenerateCollider(shapes[i], shapeExt,
                                                                                                out float3 offsetPosition, out quaternion offsetRotation);
                        blobs.Add(new CompoundCollider.ColliderBlobInstance
                        {
                            CompoundFromChild = new RigidTransform(children[i].rotation, children[i].position - this.transform.position),
                            Collider          = collider
                        });
                        var ltw = new LocalToWorld {
                            Value = new float4x4(children[i].rotation, children[i].position - this.transform.position)
                        };
                        buffer.Add(new PhysicsColliderFollowEntityData
                        {
                            AnimationDataIndex         = i,
                            CompoundColliderChildIndex = blobs.Length - 1,
                            RootTransform             = new RigidTransform(InitialRootRotation, InitialRootPosition),
                            sourceEntity              = conversionSystem.GetPrimaryEntity(shapes[i].gameObject),
                            CompoundColliderDataIsSet = false,
                            Old    = ltw,
                            Offset = ltw
                        });
                        Debug.Log("Setting \"" + children[i].name + "\" to " + (blobs.Length - 1) + " animation index =" + i + ", valid shapes = " + numberOfValidShapes + ", belongs to " + shapes[i].BelongsTo.Value + ", collides with = " + shapes[i].CollidesWith.Value);

                        //   shapes[i].enabled = false;
                    }
                }
                if (blobs.Length > 0)
                {
                    dstManager.AddComponentData(entity, new PhysicsCollider {
                        Value = CompoundCollider.Create(blobs)
                    });
                }

                blobs.Dispose();
            }
            else if (children.Length == 1)
            {
                dstManager.AddComponentData(entity, new PhysicsCollider {
                    Value = GenerateCollider(shapes[0], null, out var a, out var b)
                });
        unsafe public static AnimationStream CreateReadOnly(BlobAssetReference <RigDefinition> rig, NativeArray <AnimatedData> buffer)
        {
            if (rig == default || buffer.Length == 0 || buffer.Length != rig.Value.Bindings.StreamSize)
            {
                return(AnimationStream.Null);
            }

            return(AnimationStream.Create(rig, buffer.GetUnsafeReadOnlyPtr()));
        }
Example #7
0
        public Entity CreateDynamicSphere(RenderMesh displayMesh, float radius, float3 position, quaternion orientation)
        {
            // Sphere with default filter and material. Add to Create() call if you want non default:
            BlobAssetReference <Unity.Physics.Collider> spCollider = Unity.Physics.SphereCollider.Create(float3.zero, radius, new CollisionFilter {
                BelongsTo = TriggerEventClass.NPC, CollidesWith = uint.MaxValue, GroupIndex = 0
            });

            return(CreateBody(displayMesh, position, orientation, spCollider, float3.zero, float3.zero, 1.0f, true));
        }
            public static BlobData Create <T0>(BlobAssetReference <T0> reference, int identifier)
                where T0 : struct
            {
                BlobData blobData = default;

                UnsafeUtility.CopyStructureToPtr(ref reference, &blobData.m_blobRef);

                return(blobData);
            }
        void ResolveScene(Entity sceneEntity, ref SceneReference scene, RequestSceneLoaded requestSceneLoaded, Hash128 artifactHash)
        {
            // Resolve first (Even if the file doesn't exist we want to stop continously trying to load the section)
            EntityManager.AddBuffer <ResolvedSectionEntity>(sceneEntity);

#if UNITY_EDITOR && !USE_SUBSCENE_EDITORBUNDLES
            EntityManager.AddComponentData(sceneEntity, new ResolvedSceneHash {
                ArtifactHash = artifactHash
            });

            UnityEditor.Experimental.AssetDatabaseExperimental.GetArtifactPaths(artifactHash, out var paths);

            var sceneHeaderPath = EntityScenesPaths.GetLoadPathFromArtifactPaths(paths, EntityScenesPaths.PathType.EntitiesHeader);
#else
            var sceneHeaderPath = EntityScenesPaths.GetLoadPath(scene.SceneGUID, EntityScenesPaths.PathType.EntitiesHeader, -1);
#endif

#if UNITY_ANDROID && !UNITY_EDITOR
            var uwrFile = new UnityWebRequest(sceneHeaderPath);
            uwrFile.downloadHandler = new DownloadHandlerBuffer();
            uwrFile.SendWebRequest();
            while (!uwrFile.isDone)
            {
            }

            if (uwrFile.isNetworkError || uwrFile.isHttpError)
            {
                Debug.LogError($"Loading Entity Scene failed because the entity header file could not be found: {scene.SceneGUID}\nNOTE: In order to load SubScenes in the player you have to use the new BuildSettings asset based workflow to build & run your player.\n{sceneHeaderPath}");
                return;
            }

            if (!BlobAssetReference <SceneMetaData> .TryRead(uwrFile.downloadHandler.data, SceneMetaDataSerializeUtility.CurrentFileFormatVersion, out var sceneMetaDataRef))
            {
                Debug.LogError("Loading Entity Scene failed because the entity header file was an old version: " + scene.SceneGUID);
                return;
            }
#else
            if (!File.Exists(sceneHeaderPath))
            {
                #if UNITY_EDITOR
                Debug.LogError($"Loading Entity Scene failed because the entity header file could not be found: {scene.SceneGUID}\n{sceneHeaderPath}");
                #else
                Debug.LogError($"Loading Entity Scene failed because the entity header file could not be found: {scene.SceneGUID}\nNOTE: In order to load SubScenes in the player you have to use the new BuildSettings asset based workflow to build & run your player.\n{sceneHeaderPath}");
                #endif
                return;
            }

            if (!BlobAssetReference <SceneMetaData> .TryRead(sceneHeaderPath, SceneMetaDataSerializeUtility.CurrentFileFormatVersion, out var sceneMetaDataRef))
            {
                Debug.LogError("Loading Entity Scene failed because the entity header file was an old version: " + scene.SceneGUID);
                return;
            }
#endif

            LogResolving("ResolveScene (success)", scene.SceneGUID);

            ref var sceneMetaData = ref sceneMetaDataRef.Value;
        /// <summary>
        /// Given a clip and frame, creates a blob asset of a single pose at that frame
        /// </summary>
        /// <param name="source"></param>
        /// <param name="frame"></param>
        /// <returns></returns>
        public static unsafe BlobAssetReference <Clip> CreatePose(BlobAssetReference <Clip> source, int frame = 0)
        {
            if (source == BlobAssetReference <Clip> .Null)
            {
                return(BlobAssetReference <Clip> .Null);
            }

            var     blobBuilder = new BlobBuilder(Allocator.Temp);
            ref var clip        = ref blobBuilder.ConstructRoot <Clip>();
Example #11
0
 protected override void OnCreate()
 {
     base.OnCreate();
     _droneUid           = 0;
     _droneMesh          = AssetData.Drone.ToRenderMesh();
     _propellerMesh      = AssetData.Drone.ToPropellerMesh();
     _propellerPositions = AssetData.Drone.PropellerPositions;
     _droneCollider      = AssetData.Drone.BoxCollider;
 }
Example #12
0
    internal override void ConfigureInstance(Entity instance, ref SpawnExplosionSettings spawnSettings)
    {
        // Create single collider per Explosion group
        if (GroupId != spawnSettings.Id)
        {
            GroupId = spawnSettings.Id;
            spawnSettings.Source = instance;

            var collider  = EntityManager.GetComponentData <PhysicsCollider>(instance);
            var memsize   = collider.Value.Value.MemorySize;
            var oldFilter = collider.Value.Value.Filter;

            // Only one of these needed per group, since all debris within
            // a group will share a single collider
            // This will make debris within a group collide some time after the explosion happens
            EntityManager.AddComponentData(instance, new ChangeFilterCountdown
            {
                Countdown = spawnSettings.Countdown * 2,
                Filter    = oldFilter
            });

            // Make unique collider for each spawned group
            unsafe
            {
                // Create new collider for the group
                // TODO : make Collider ICloneable
                BlobAssetReference <Collider> colliderCopy = BlobAssetReference <Collider> .Create(UnsafeUtility.Malloc(memsize, 16, Allocator.Persistent), memsize);

                UnsafeUtility.MemCpy(colliderCopy.GetUnsafePtr(), collider.ColliderPtr, memsize);

                // Set the GroupIndex to GroupId, which is negative
                // This ensures that the debris within a group don't collide
                colliderCopy.Value.Filter = new CollisionFilter
                {
                    BelongsTo    = oldFilter.BelongsTo,
                    CollidesWith = oldFilter.CollidesWith,
                    GroupIndex   = GroupId,
                };
                PhysicsCollider newCollider = new PhysicsCollider
                {
                    Value = colliderCopy
                };
                GroupCollider = newCollider;
                CreatedColliders.Add(GroupCollider);
            }
        }

        EntityManager.SetComponentData(instance, GroupCollider);

        EntityManager.AddComponentData(instance, new ExplosionCountdown
        {
            Source    = spawnSettings.Source,
            Countdown = spawnSettings.Countdown,
            Center    = spawnSettings.Position,
            Force     = spawnSettings.Force
        });
    }
Example #13
0
 protected override void OnCreate()
 {
     base.OnCreate();
     _buildQueue  = new NativeQueue <float4>(Allocator.Persistent);
     _hubUid      = 0;
     _hub         = Archetypes.Hub;
     _hubMesh     = AssetData.Hub.ToRenderMesh();
     _hubCollider = AssetData.Hub.BoxCollider;
 }
        protected override void OnCreate()
        {
            _entityCommandBufferSystem = World.GetOrCreateSystem <BeginInitializationEntityCommandBufferSystem>();
            _buildPhysicsWorldSystem   = World.GetOrCreateSystem <BuildPhysicsWorld>();

            _query = GetEntityQuery(new EntityQueryDesc()
            {
                All = new ComponentType[] {
                    ComponentType.ReadOnly <Translation>(),
                    ComponentType.ReadOnly <Rotation>(),
                    typeof(PhysicsVelocity),
                    ComponentType.ReadOnly <PhysicsMass>(),
                    typeof(FighterComponent),
                },
            });
            _targetableQuery = GetEntityQuery(new EntityQueryDesc()
            {
                All = new ComponentType[] {
                    ComponentType.ReadOnly <FighterTargetable>(),
                },
            });

#if SEARCHING
            cast_collider_ = SphereCollider.Create(new float3(0, 0, 0) /* center */,
                                                   1f /* radius */,
                                                   new CollisionFilter {
                BelongsTo    = ~0u,
                CollidesWith = ~0u,
            },
                                                   null /* material */);

            // create approximate hexagonal directions.
            //      2
            //   6     4
            //      0
            //   5     3
            //      1
            local_search_rotations_    = new NativeArray <quaternion>(FighterConfig.SEARCH_NUM, Allocator.Persistent);
            local_search_rotations_[0] = quaternion.Euler(0, 0, 0);
            local_search_rotations_[1] = quaternion.Euler(math.radians(10f), 0, 0);
            local_search_rotations_[2] = quaternion.Euler(math.radians(-10f), 0, 0);
            local_search_rotations_[3] = quaternion.Euler(math.radians(5f), math.radians(5f * 1.7320508f), 0);
            local_search_rotations_[4] = quaternion.Euler(math.radians(-5f), math.radians(5f * 1.7320508f), 0);
            local_search_rotations_[5] = quaternion.Euler(math.radians(5f), math.radians(-5f * 1.7320508f), 0);
            local_search_rotations_[6] = quaternion.Euler(math.radians(-5f), math.radians(-5f * 1.7320508f), 0);
#endif

            _lastPrimaryFighterPos = new NativeArray <float3>(1, Allocator.Persistent);
            _lastPrimaryTargetPos  = new NativeArray <float3>(1, Allocator.Persistent);
        #if RECORDING
            controller_buffer_ = new NativeList <ControllerUnit>(ControllerBuffer.MAX_FRAMES, Allocator.Persistent);
            controller_device_ = new ControllerDevice(controller_buffer_);
            controller_device_.start(Time.GetCurrent());
        #else
            _controllerBuffer = ControllerBuffer.Load <ControllerUnit>("controller.bin");
        #endif
        }
    // Static and dynamic rigid bodies
    public unsafe void CreateRigidBodies()
    {
        NativeSlice <RigidBody> dynamicBodies = PhysicsWorld.DynamicBodies;
        NativeSlice <RigidBody> staticBodies  = PhysicsWorld.StaticBodies;

        // Creating dynamic bodies
        {
            NativeArray <CustomCollider>    colliders  = CustomDynamicEntityGroup.ToComponentDataArray <CustomCollider>(Allocator.TempJob);
            NativeArray <Translation>       positions  = CustomDynamicEntityGroup.ToComponentDataArray <Translation>(Allocator.TempJob);
            NativeArray <Rotation>          rotations  = CustomDynamicEntityGroup.ToComponentDataArray <Rotation>(Allocator.TempJob);
            NativeArray <PhysicsCustomTags> customTags = CustomDynamicEntityGroup.ToComponentDataArray <PhysicsCustomTags>(Allocator.TempJob);
            NativeArray <Entity>            entities   = CustomDynamicEntityGroup.ToEntityArray(Allocator.TempJob);

            for (int i = 0; i < entities.Length; i++)
            {
                dynamicBodies[i] = new RigidBody
                {
                    WorldFromBody = new RigidTransform(rotations[i].Value, positions[i].Value),
                    Collider      = BlobAssetReference <Collider> .Create(colliders[i].ColliderPtr, colliders[i].ColliderPtr->MemorySize),
                    Entity        = entities[i],
                    CustomTags    = customTags[i].Value
                };
                EntityToBodyIndexMap.Add(entities[i], i);
            }

            colliders.Dispose();
            positions.Dispose();
            rotations.Dispose();
            customTags.Dispose();
            entities.Dispose();
        }

        // Creating static bodies
        {
            NativeArray <CustomCollider>    colliders  = CustomStaticEntityGroup.ToComponentDataArray <CustomCollider>(Allocator.TempJob);
            NativeArray <Translation>       positions  = CustomStaticEntityGroup.ToComponentDataArray <Translation>(Allocator.TempJob);
            NativeArray <Rotation>          rotations  = CustomStaticEntityGroup.ToComponentDataArray <Rotation>(Allocator.TempJob);
            NativeArray <PhysicsCustomTags> customTags = CustomStaticEntityGroup.ToComponentDataArray <PhysicsCustomTags>(Allocator.TempJob);
            NativeArray <Entity>            entities   = CustomStaticEntityGroup.ToEntityArray(Allocator.TempJob);

            for (int i = 0; i < entities.Length; i++)
            {
                staticBodies[i] = new RigidBody
                {
                    WorldFromBody = new RigidTransform(rotations[i].Value, positions[i].Value),
                    Collider      = BlobAssetReference <Collider> .Create(colliders[i].ColliderPtr, colliders[i].ColliderPtr->MemorySize),
                    Entity        = entities[i],
                    CustomTags    = customTags[i].Value
                };
                EntityToBodyIndexMap.Add(entities[i], i + dynamicBodies.Length);
            }

            // default static body
            staticBodies[entities.Length] = new RigidBody
            {
                WorldFromBody = new RigidTransform(quaternion.identity, float3.zero),
                Collider      = default,
Example #16
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
#if DOTS
        float Width          = 1f;
        float SampleSpacing  = 0.25f;
        float ChannelSpacing = 0f;

        JobHandle job = new JobHandle();

        MusicVisualManager musicVis = MusicVisualManager.instance;

        bool musicValid = musicVis != null;
        if (musicValid)
        {
            BlobAssetReference <MusicDataBlobAsset> SampleData = new BlobAssetReference <MusicDataBlobAsset>();

            musicVis.GetSampleData(ref SampleData, out float sampleScale, out int SampleCount);

            job = Entities.ForEach((ref Translation trans, ref NonUniformScale scale, ref VisualizerData visData) =>
            {
                // if(visData.MusicData.IsCreated)
                // {
                //     #if true
                //     visData.SampleValue = SampleData.Value.sampleArray[(visData.Channel * SampleCount) + visData.index].Value * sampleScale;
                //     #else
                //     visData.SampleValue = visData.MusicData.Value.sampleArray[(visData.Channel * SampleCount) + visData.index].Value * sampleScale;
                //     #endif
                // }
                // else
                // {
                //     visData.SampleValue = 0f;
                // }
                visData.SampleValue = SampleData.Value.sampleArray[(visData.Channel * SampleCount) + visData.index].Value * sampleScale;

                trans.Value.x = visData.index * (Width + SampleSpacing);
                trans.Value.y = (ChannelSpacing * visData.Channel) + visData.SampleValue / 2f;

                scale.Value.x = Width;
                scale.Value.y = visData.SampleValue;
            }).Schedule(inputDeps);
        }
        else
        {
            job = Entities.ForEach((ref Translation trans, ref NonUniformScale scale, ref VisualizerData visData) =>
            {
                trans.Value.x = visData.index * (Width + SampleSpacing);
                trans.Value.y = (ChannelSpacing * visData.Channel) + visData.SampleValue / 2f;

                scale.Value.x = Width;
                scale.Value.y = visData.SampleValue;
            }).Schedule(inputDeps);
        }

        return(job);
#else
        return(default);
    protected override void Start()
    {
        base.Start();
        //base.init(float3.zero); // no gravity

        // Enable the joint viewer
        SetDebugDisplay(new Unity.Physics.Authoring.PhysicsDebugDisplayData
        {
            DrawJoints   = 1,
            DrawContacts = 1
        });

        const uint layerBody     = (1 << 0);
        const uint layerHead     = (1 << 1);
        const uint layerUpperArm = (1 << 2);
        const uint layerForearm  = (1 << 3);
        const uint layerHand     = (1 << 4);
        const uint layerThigh    = (1 << 5);
        //         const uint layerCalf = (1 << 6);
        //         const uint layerFoot = (1 << 7);
        const int layerGround = (1 << 8);

        // Floor
        {
            BlobAssetReference <Collider> collider = BoxCollider.Create(float3.zero, Quaternion.identity, new float3(20.0f, 0.2f, 20.0f), 0.01f, filter(layerGround, 0));
            CreateStaticBody(new float3(0, -0.1f, 0), quaternion.identity, collider);
        }

        // Body
        float3 bodyHalfExtents = new float3(0.2f, 0.3f, 0.075f);
        float3 bodyPosition    = new float3(0, 0.1f, 0);
        Entity body;
        {
            BlobAssetReference <Collider> collider = BoxCollider.Create(
                float3.zero, Quaternion.identity, 2.0f * bodyHalfExtents, 0.01f, filter(layerBody, layerHead | layerUpperArm | layerThigh));
            quaternion q = quaternion.AxisAngle(new float3(1, 0, 0), (float)math.PI / 2.0f);
            body = CreateDynamicBody(bodyPosition, quaternion.identity, collider, float3.zero, float3.zero, 10.0f);
            //body = createStaticBody(bodyPosition, quaternion.identity, collider);
        }

        // Arms
        {
            float handLength = 0.025f;
            float handRadius = 0.055f;
            BlobAssetReference <Collider> handCollider = CapsuleCollider.Create(new float3(-handLength / 2, 0, 0), new float3(handLength / 2, 0, 0), handRadius,
                                                                                filter(layerHand, layerForearm));

            for (int i = 0; i < 1; i++)
            {
                float s = i * 2 - 1.0f;

                float3 handPosition = new float3(0, 0.3f, 0);
                Entity hand         = CreateDynamicBody(handPosition, quaternion.identity, handCollider, float3.zero, float3.zero, 10.0f);
            }
        }
    }
Example #18
0
        public static void AddBehaviorTree(
            this Entity entity
            , EntityManager dstManager
            , BlobAssetReference <NodeBlob> blobRef
            , BehaviorTreeThread thread = BehaviorTreeThread.ForceRunOnMainThread
            )
        {
            var blob = new NodeBlobRef {
                BlobRef = blobRef
            };

            switch (thread)
            {
            case BehaviorTreeThread.ForceRunOnMainThread:
            {
                var bb = new EntityBlackboard {
                    EntityManager = dstManager, Entity = entity
                };
                VirtualMachine.Reset(blob, bb);
                dstManager.AddComponentData(entity, new ForceRunOnMainThreadTag());
                break;
            }

            case BehaviorTreeThread.ForceRunOnJob:
            {
                AddJobComponents();
                dstManager.AddComponentData(entity, new ForceRunOnJobTag());
                break;
            }

            case BehaviorTreeThread.ControlledByBehaviorTree:
            {
                AddJobComponents();
                break;
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(thread), thread, null);
            }

            dstManager.AddComponentData(entity, blob);

            void AddJobComponents()
            {
                var dataQuery = new BlackboardDataQuery {
                    Value = blobRef.GetAccessTypes()
                };
                var bb = new EntityBlackboard();

                VirtualMachine.Reset(blob, bb);
                dstManager.AddComponentData(entity, new IsRunOnMainThread {
                    Value = false
                });
                dstManager.AddSharedComponentData(entity, dataQuery);
            }
        }
Example #19
0
        public unsafe void EntityDiffer_GetChanges_BlobAssets_SetComponent_TypeMemoryOrdering()
        {
            using (var differ = new EntityManagerDiffer(SrcEntityManager, Allocator.TempJob))
            {
                var blobAssetReferences = new NativeArray <BlobAssetReference <int> >(100, Allocator.Temp);

                for (var i = 0; i < blobAssetReferences.Length; i++)
                {
                    // Construct the archetype in an order which will NOT match the memory order.
                    var archetype = SrcEntityManager.CreateArchetype(
                        typeof(EntityGuid),
                        typeof(EcsTestDataBlobAssetRef),
                        typeof(EcsTestData4));

                    // Validate the assumption that the archetype is created in this way.
                    Assert.That(archetype.Archetype->TypeMemoryOrder[0], Is.EqualTo(0));
                    Assert.That(archetype.Archetype->TypeMemoryOrder[1], Is.EqualTo(2));
                    Assert.That(archetype.Archetype->TypeMemoryOrder[2], Is.EqualTo(1));

                    // Validate the component sizes are different
                    Assert.That(UnsafeUtility.SizeOf <EcsTestDataBlobAssetRef>(), Is.Not.EqualTo(UnsafeUtility.SizeOf <EcsTestData4>()));

                    var entity = SrcEntityManager.CreateEntity(archetype);

                    blobAssetReferences[i] = BlobAssetReference <int> .Create(i);

                    SrcEntityManager.SetComponentData(entity, CreateEntityGuid());
                    SrcEntityManager.SetComponentData(entity, new EcsTestData4());
                    SrcEntityManager.SetComponentData(entity, new EcsTestDataBlobAssetRef
                    {
                        value = blobAssetReferences[i]
                    });
                }

                try
                {
                    using (var changes = differ.GetChanges(EntityManagerDifferOptions.Default, Allocator.Temp))
                    {
                        Assert.IsTrue(changes.HasForwardChangeSet);
                        var forward = changes.ForwardChangeSet;
                        Assert.That(forward.CreatedBlobAssets.Length, Is.EqualTo(100));
                        Assert.That(forward.BlobAssetReferenceChanges.Length, Is.EqualTo(100));
                        Assert.That(forward.BlobAssetData.Length, Is.EqualTo(sizeof(int) * 100));
                    }
                }
                finally
                {
                    for (var i = 0; i < blobAssetReferences.Length; i++)
                    {
                        blobAssetReferences[i].Dispose();
                    }

                    blobAssetReferences.Dispose();
                }
            }
        }
Example #20
0
        //Adds a dynamic box to the world
        static public unsafe void addDynamicBoxToWorld(Physics.PhysicsWorld world, int index, Vector3 pos, Quaternion orientation, Vector3 size)
        {
            Assert.IsTrue(index < world.NumDynamicBodies, "Dynamic body index is out of range in addDynamicBoxToWorld");
            Unity.Collections.NativeSlice <Physics.RigidBody> dynamicBodies = world.DynamicBodies;
            Physics.RigidBody rb = dynamicBodies[index];
            BlobAssetReference <Physics.Collider> collider = Unity.Physics.BoxCollider.Create(pos, orientation, size, .01f);

            rb.Collider          = (Collider *)collider.GetUnsafePtr();
            dynamicBodies[index] = rb;
        }
Example #21
0
        public static BlobAssetReference <NodeBlob> ToBlob(this TextAsset file)
        {
            var result = BlobAssetReference <NodeBlob> .TryRead(file.bytes, NodeBlob.VERSION, out var blobRef);

            if (!result)
            {
                throw new FormatException("Version is not match.");
            }
            return(blobRef);
        }
Example #22
0
 public SingletonColorBlob(BlobAssetReference <ColorArray> provinces,
                           BlobAssetReference <ColorArray> areas,
                           BlobAssetReference <ColorArray> regions,
                           BlobAssetReference <ColorArray> supers)
 {
     Provinces = provinces;
     Areas     = areas;
     Regions   = regions;
     Supers    = supers;
 }
Example #23
0
        public void EntityDiffer_GetChanges_BlobAssets_SetBuffer_MultipleEntities()
        {
            using (var differ = new EntityManagerDiffer(SrcEntityManager, Allocator.TempJob))
            {
                var blobAssetReferences = new NativeArray <BlobAssetReference <int> >(100, Allocator.Temp);

                for (var i = 0; i < blobAssetReferences.Length; i++)
                {
                    blobAssetReferences[i] = BlobAssetReference <int> .Create(i);
                }

                for (var i = 0; i < blobAssetReferences.Length; i += 4)
                {
                    var entity = SrcEntityManager.CreateEntity(typeof(EntityGuid));

                    SrcEntityManager.SetComponentData(entity, CreateEntityGuid());

                    var buffer = SrcEntityManager.AddBuffer <EcsTestDataBlobAssetElement>(entity);

                    buffer.Add(new EcsTestDataBlobAssetElement {
                        blobElement = blobAssetReferences[i + 0]
                    });
                    buffer.Add(new EcsTestDataBlobAssetElement {
                        blobElement = blobAssetReferences[i + 1]
                    });
                    buffer.Add(new EcsTestDataBlobAssetElement {
                        blobElement = blobAssetReferences[i + 2]
                    });
                    buffer.Add(new EcsTestDataBlobAssetElement {
                        blobElement = blobAssetReferences[i + 3]
                    });
                }

                try
                {
                    using (var changes = differ.GetChanges(EntityManagerDifferOptions.Default, Allocator.Temp))
                    {
                        Assert.IsTrue(changes.HasForwardChangeSet);
                        var forward = changes.ForwardChangeSet;
                        Assert.That(forward.CreatedBlobAssets.Length, Is.EqualTo(100));
                        Assert.That(forward.BlobAssetReferenceChanges.Length, Is.EqualTo(100));
                        Assert.That(forward.BlobAssetData.Length, Is.EqualTo(sizeof(int) * 100));
                    }
                }
                finally
                {
                    for (var i = 0; i < blobAssetReferences.Length; i++)
                    {
                        blobAssetReferences[i].Dispose();
                    }

                    blobAssetReferences.Dispose();
                }
            }
        }
    public override void CreateScene(CompoundDemoScene sceneSettings)
    {
        //         // Floor
        //         {
        //             BlobAssetReference<Unity.Physics.Collider> collider = Unity.Physics.BoxCollider.Create(new float3(0, -0.1f, 0), Quaternion.identity, new float3(10.0f, 0.1f, 10.0f), 0.05f);
        //             CreatedColliders.Add(collider);
        //             CreateStaticBody(float3.zero, quaternion.identity, collider);
        //         }

        // Dynamic compound
        {
            var box = new BoxGeometry
            {
                Center      = float3.zero,
                Orientation = quaternion.identity,
                Size        = new float3(1),
                BevelRadius = 0.05f
            };

            var sphere = new SphereGeometry
            {
                Center = float3.zero,
                Radius = 0.5f
            };

            var children = new NativeArray <CompoundCollider.ColliderBlobInstance>(3, Allocator.Temp)
            {
                [0] = new CompoundCollider.ColliderBlobInstance
                {
                    CompoundFromChild = new RigidTransform(quaternion.identity, new float3(-1, 0, 0)),
                    Collider          = Unity.Physics.BoxCollider.Create(box)
                },
                [1] = new CompoundCollider.ColliderBlobInstance
                {
                    CompoundFromChild = RigidTransform.identity,
                    Collider          = Unity.Physics.SphereCollider.Create(sphere)
                },
                [2] = new CompoundCollider.ColliderBlobInstance
                {
                    CompoundFromChild = new RigidTransform(quaternion.identity, new float3(1, 0, 0)),
                    Collider          = Unity.Physics.BoxCollider.Create(box)
                }
            };
            foreach (var child in children)
            {
                CreatedColliders.Add(child.Collider);
            }

            BlobAssetReference <Unity.Physics.Collider> collider = CompoundCollider.Create(children);
            CreatedColliders.Add(collider);
            children.Dispose();

            CreateDynamicBody(new float3(0, 1, 0), quaternion.identity, collider, float3.zero, float3.zero, 1.0f);
        }
    }
Example #25
0
    public override void CreateScene(InvalidPhysicsJointExcludeDemoScene sceneSettings)
    {
        float colliderSize = 0.25f;

        BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.BoxCollider.Create(new BoxGeometry
        {
            Center      = float3.zero,
            Orientation = quaternion.identity,
            Size        = new float3(colliderSize),
            BevelRadius = 0.0f
        });

        CreatedColliders.Add(collider);

        float timeToSwap = sceneSettings.TimeToSwap;

        var bodyAPos = new float3(2f, 5.0f, 2);
        var bodyBPos = new float3(2f, 6.0f, 2);

        // Add constrained dynamic/dynamic body pair that will have their bodies excluded
        bool buildThisSection = true;

        if (buildThisSection)
        {
            bodyAPos += new float3(1, 0, 0);
            bodyBPos += new float3(1, 0, 0);

            // Create a body
            Entity bodyA = CreateDynamicBody(bodyAPos, quaternion.identity, collider, float3.zero, float3.zero, 1.0f);
            Entity bodyB = CreateDynamicBody(bodyBPos, quaternion.identity, collider, float3.zero, float3.zero, 1.0f);

            for (int i = 0; i < 2; i++)
            {
                // Create the joint
                var joint       = PhysicsJoint.CreateBallAndSocket(new float3(0, colliderSize, 0), new float3(0, -colliderSize, 0));
                var jointEntity = CreateJoint(joint, bodyA, bodyB);

                var pair = EntityManager.GetComponentData <PhysicsConstrainedBodyPair>(jointEntity);
                pair.EnableCollision = 1;
                EntityManager.SetComponentData(jointEntity, pair);
            }

            // add exclude components.
            EntityManager.AddComponentData(bodyA, new InvalidPhysicsJointExcludeBodies {
            });
            EntityManager.AddComponentData(bodyA, new InvalidPhysicsJointExcludeTimerEvent {
                TimeLimit = timeToSwap, Timer = timeToSwap
            });
            EntityManager.AddComponentData(bodyB, new InvalidPhysicsJointExcludeBodies {
            });
            EntityManager.AddComponentData(bodyB, new InvalidPhysicsJointExcludeTimerEvent {
                TimeLimit = timeToSwap, Timer = timeToSwap
            });
        }
    }
Example #26
0
    protected override unsafe void Start()
    {
        init();

        BlobAssetReference <Collider> collider = BoxCollider.Create(new BoxGeometry
        {
            Center      = float3.zero,
            Orientation = quaternion.identity,
            Size        = new float3(0.2f, 0.2f, 0.2f),
            BevelRadius = 0.0f
        });

        // Make some 1d angular limit joints
        const int   size  = 6;
        const float speed = 1.0f;
        int         iDbg  = 0;
        int         jDbg  = 3;

        for (int i = 0; i < size; i++)
        {
            quaternion q1 = quaternion.AxisAngle(new float3(1, 0, 0), (float)math.PI * 2.0f * i / size);
            for (int j = 0; j < size; j++)
            {
                if (iDbg >= 0 && jDbg >= 0 && (i != iDbg || j != jDbg))
                {
                    continue;
                }

                // Choose the limited axis
                quaternion q2 = quaternion.AxisAngle(math.mul(q1, new float3(0, 1, 0)),
                                                     (float)math.PI * ((float)j / size));

                // Create a body with some angular velocity about the axis
                float3 pos  = new float3(i - (size - 1) / 2.0f, 0, j - (size - 1) / 2.0f);
                Entity body = CreateDynamicBody(pos, quaternion.identity, collider, float3.zero,
                                                math.mul(q2, new float3(speed, 0, 0)), 1.0f);

                // Create a 1D angular limit about the axis
                float3x3 rotationB = float3x3.identity;
                float3x3 rotationA = math.mul(new float3x3(q2), rotationB);
                var      jointData = new PhysicsJoint
                {
                    BodyAFromJoint = new RigidTransform(rotationA, new float3(0, 0, 0)),
                    BodyBFromJoint = new RigidTransform(rotationB, pos)
                };
                jointData.SetConstraints(new FixedList128 <Constraint>
                {
                    Length = 1,
                    [0]    = Constraint.Twist(0, new FloatRange(-math.PI / 4f, math.PI / 4f))
                });

                CreateJoint(jointData, body, Entity.Null);
            }
        }
    }
        unsafe void ReceiveResponseSubSceneTargetHash(MessageEventArgs args)
        {
            using (var subSceneAssets = args.ReceiveArray <ResolvedSubSceneID>())
            {
                foreach (var subSceneAsset in subSceneAssets)
                {
                    if (_WaitingForSubScenes.ContainsKey(subSceneAsset.SubSceneGUID))
                    {
                        return;
                    }

                    var headerPath = EntityScenesPaths.GetLiveLinkCachePath(subSceneAsset.TargetHash, EntityScenesPaths.PathType.EntitiesHeader, -1);

                    if (File.Exists(headerPath))
                    {
                        LiveLinkMsg.LogInfo($"ReceiveResponseSubSceneTargetHash => {subSceneAsset.SubSceneGUID} | {subSceneAsset.TargetHash}, File.Exists => 'True', {Path.GetFullPath(headerPath)}");

                        //TODO: This is a hack to make sure assets are managed by asset manifest when loading from cache for first run
                        if (!BlobAssetReference <SceneMetaData> .TryRead(headerPath, SceneMetaDataSerializeUtility.CurrentFileFormatVersion, out var sceneMetaDataRef))
                        {
                            Debug.LogError("Loading Entity Scene failed because the entity header file was an old version: " + subSceneAsset.SubSceneGUID);
                            return;
                        }

                        ref var sceneMetaData = ref sceneMetaDataRef.Value;

                        var waitingSubScene = new WaitingSubScene
                        {
                            TargetHash      = subSceneAsset.TargetHash,
                            SubSections     = new List <NativeArray <RuntimeGlobalObjectId> >(),
                            SubSectionCount = sceneMetaData.Sections.Length
                        };

                        for (int i = 0; i < sceneMetaData.Sections.Length; i++)
                        {
                            if (sceneMetaData.Sections[i].ObjectReferenceCount != 0)
                            {
                                var refObjGUIDsPath = EntityScenesPaths.GetLiveLinkCachePath(subSceneAsset.TargetHash, EntityScenesPaths.PathType.EntitiesUnityObjectReferences, i);
                                using (var reader = new StreamBinaryReader(refObjGUIDsPath))
                                {
                                    var numObjRefGUIDs = reader.ReadInt();
                                    NativeArray <RuntimeGlobalObjectId> objRefGUIDs = new NativeArray <RuntimeGlobalObjectId>(numObjRefGUIDs, Allocator.Persistent);
                                    reader.ReadArray(objRefGUIDs, numObjRefGUIDs);
                                    waitingSubScene.SubSections.Add(objRefGUIDs);
                                }
                            }
                            else
                            {
                                waitingSubScene.SubSections.Add(new NativeArray <RuntimeGlobalObjectId>(0, Allocator.Persistent));
                            }
                        }

                        _WaitingForSubScenes[subSceneAsset.SubSceneGUID] = waitingSubScene;
                    }
Example #28
0
    internal static BlobAssetReference <T> LoadAsset <T>(WeakAssetReference assetRef) where T : struct
    {
        var path = GetBlobAssetPath(assetRef.GetGuidStr());

        if (!File.Exists(path))
        {
            throw new FileNotFoundException("Cannot find file:" + path);
        }

        return(BlobAssetReference <T> .Create(File.ReadAllBytes(path)));
    }
Example #29
0
    protected unsafe override void Start()
    {
        //float3 gravity = new float3(0, -9.81f, 0);
        float3 gravity = float3.zero;

        base.init(gravity);

        //         // Floor
        //         {
        //             BlobAssetReference<Unity.Physics.Collider> collider = Unity.Physics.BoxCollider.Create(new float3(0, -0.1f, 0), Quaternion.identity, new float3(10.0f, 0.1f, 10.0f), 0.05f);
        //             CreateStaticBody(float3.zero, quaternion.identity, collider);
        //         }

        // Dynamic compound
        {
            var box = new BoxGeometry
            {
                Center      = float3.zero,
                Orientation = quaternion.identity,
                Size        = new float3(1),
                BevelRadius = 0.05f
            };

            var sphere = new SphereGeometry
            {
                Center = float3.zero,
                Radius = 0.5f
            };

            var children = new NativeArray <CompoundCollider.ColliderBlobInstance>(3, Allocator.Temp)
            {
                [0] = new CompoundCollider.ColliderBlobInstance
                {
                    CompoundFromChild = new RigidTransform(quaternion.identity, new float3(-1, 0, 0)),
                    Collider          = Unity.Physics.BoxCollider.Create(box)
                },
                [1] = new CompoundCollider.ColliderBlobInstance
                {
                    CompoundFromChild = RigidTransform.identity,
                    Collider          = Unity.Physics.SphereCollider.Create(sphere)
                },
                [2] = new CompoundCollider.ColliderBlobInstance
                {
                    CompoundFromChild = new RigidTransform(quaternion.identity, new float3(1, 0, 0)),
                    Collider          = Unity.Physics.BoxCollider.Create(box)
                }
            };

            BlobAssetReference <Unity.Physics.Collider> collider = CompoundCollider.Create(children);
            children.Dispose();

            CreateDynamicBody(new float3(0, 1, 0), quaternion.identity, collider, float3.zero, float3.zero, 1.0f);
        }
    }
Example #30
0
 public static void SetRig(NodeSet set, ref DynamicMixer dynamicMixer, DynamicBuffer <DynamicMixerInput> inputs,
                           BlobAssetReference <RigDefinition> rig)
 {
     dynamicMixer.Rig = rig;
     set.SendMessage(dynamicMixer.MixerBegin, MixerBeginNode.SimulationPorts.RigDefinition, rig);
     set.SendMessage(dynamicMixer.MixerEnd, MixerEndNode.SimulationPorts.RigDefinition, rig);
     for (int i = 0; i < inputs.Length; i++)
     {
         set.SendMessage(inputs[i].AddNode, MixerAddNode.SimulationPorts.RigDefinition, rig);
     }
 }