private IEnumerator RemoveInstancesAtRuntime() { for (int i = 0; i < instanceCount; i++) { if (!instancesList[instancesList.Count - 1].prefabPrototype.addRuntimeHandlerScript) { GPUInstancerAPI.RemovePrefabInstance(prefabManager, instancesList[instancesList.Count - 1]); } Destroy(instancesList[instancesList.Count - 1].gameObject); instancesList.RemoveAt(instancesList.Count - 1); if (!addRemoveInstantlyToggle.isOn) { yield return(new WaitForSeconds(0.001f)); } } EnableButton("AddInstancesButton"); if (extraInstancesList.Count == 0) { EnableButton("AddExtraInstancesButton"); } else { EnableButton("RemoveExtraInstancesButton"); } }
void Start() { goList = new List <GPUInstancerPrefab>(); // Define the buffer to the Prefab Manager. if (prefabManager != null && prefabManager.isActiveAndEnabled) { GPUInstancerAPI.DefinePrototypeVariationBuffer <Vector4>(prefabManager, prefab.prefabPrototype, bufferName); } // Generate instances inside a radius. for (int i = 0; i < instances; i++) { GPUInstancerPrefab prefabInstance = Instantiate(prefab); prefabInstance.transform.localPosition = Random.insideUnitSphere * 20; prefabInstance.transform.SetParent(transform); goList.Add(prefabInstance); // Register the variation buffer for this instance. prefabInstance.AddVariation(bufferName, (Vector4)Random.ColorHSV()); } // Register the generated instances to the manager and initialize the manager. if (prefabManager != null && prefabManager.isActiveAndEnabled) { GPUInstancerAPI.RegisterPrefabInstanceList(prefabManager, goList); GPUInstancerAPI.InitializeGPUInstancer(prefabManager); } }
private IEnumerator AddInstancesAtRuntime() { for (int i = 0; i < instanceCount; i++) { GPUInstancerPrefab prefabInstance = Instantiate(prefab); prefabInstance.transform.localPosition = Random.insideUnitSphere * 10; prefabInstance.transform.SetParent(parentTransform); if (!prefabInstance.prefabPrototype.addRuntimeHandlerScript) { GPUInstancerAPI.AddPrefabInstance(prefabManager, prefabInstance); } instancesList.Add(prefabInstance); if (!addRemoveInstantlyToggle.isOn) { yield return(new WaitForSeconds(0.001f)); } } EnableButton("RemoveInstancesButton"); if (extraInstancesList.Count == 0) { EnableButton("AddExtraInstancesButton"); } else { EnableButton("RemoveExtraInstancesButton"); } }
private void Update() { if (prefabManager != null && prefabManager.isActiveAndEnabled) { Rigidbody rb; for (int i = 0; i < _enteredInstances.Count; i++) { if (!IsInsideCollider(_enteredInstances[i])) { rb = _enteredInstances[i].GetComponent <Rigidbody>(); if (rb != null && !rb.IsSleeping()) { continue; } GPUInstancerAPI.EnableInstancingForInstance(prefabManager, _enteredInstances[i]); _enteredInstances.Remove(_enteredInstances[i]); i--; } else if (_enteredInstances[i].state != PrefabInstancingState.Disabled) { prefabManager.DisableIntancingForInstance(_enteredInstances[i]); } } } }
private void Awake() { // Setup UI _uiCanvas = GameObject.Find("Canvas"); _spaceShipControlsText = GameObject.Find("SpaceShipControlsPanel"); _grassMowerControlsText = GameObject.Find("GrassMowerControlsPanel"); _loadingTerrainDetailsText = GameObject.Find("LoadingInfoPanel"); _currentQualityModeText = GameObject.Find("CurrentQualityModeInfoText").GetComponent <Text>(); _currentQualityModeText.text = "Current Quality Mode: " + _currentQualityMode + " Quality"; // Setup space ship _spaceShip = FindObjectOfType <SpaceshipController>().transform; _spaceShipThrusterGlow = _spaceShip.GetChild(0).GetChild(0).GetComponent <ParticleSystem>(); // Setup grass mower _grassMower = FindObjectOfType <GrassMowerController>().transform; // Setup camera SetCameraMode(CameraModes.FPMode); SetPrototypesByQuality(_currentQualityMode); // Setup loading bar GPUInstancerAPI.StartListeningGPUIEvent(GPUInstancerEventType.DetailInitializationFinished, DisableLoadingTerrainDetailsText); }
private void Start() { // Create a GameObject to create a prototype from prototypeGameObject = GameObject.CreatePrimitive(PrimitiveType.Quad); // Set material of the GameObject SetMaterial(); // Create a list to keep track of instances instanceList = new List <GameObject>(); // Add the original to the instanceList instanceList.Add(prototypeGameObject); // Your instantiation logic. Uses the prototype GameObject to identify the newly generated prototype. // This example just instantiates objects at random positions inside a sphere with radius of 20; // Replace this with how you want to generate your instances. for (int i = 0; i < 1000; i++) { instanceList.Add(Instantiate(prototypeGameObject, UnityEngine.Random.insideUnitSphere * 20, Quaternion.identity)); } // Define the prototype prototype = GPUInstancerAPI.DefineGameObjectAsPrefabPrototypeAtRuntime(prefabManager, prototypeGameObject); // Make changes in the prototype settings prototype.enableRuntimeModifications = true; prototype.autoUpdateTransformData = true; // Add the prototype instances GPUInstancerAPI.AddInstancesToPrefabPrototypeAtRuntime(prefabManager, prototype, instanceList); // Start Coroutine to change instances over time StartCoroutine(AddRemoveAtRuntime()); }
// Use this for initialization private void Awake() { // min buffersize check if (bufferSize < 1000) bufferSize = 1000; // initialize the array with the max size _matrix4x4Array = new Matrix4x4[bufferSize]; // change the data of the array AddMatrix4x4ToArray(1000); // initialize the buffers with array GPUInstancerAPI.InitializeWithMatrix4x4Array(prefabManager, prefab.prefabPrototype, _matrix4x4Array); GPUInstancerAPI.SetInstanceCount(prefabManager, prefab.prefabPrototype, sphereCount); // Color variatons variationData = new Vector4[bufferSize]; for (int i = 0; i < bufferSize; i++) variationData[i] = Random.ColorHSV(); GPUInstancerAPI.DefineAndAddVariationFromArray(prefabManager, prefab.prefabPrototype, bufferName, variationData); // UI CheckButtonsAvailablity(); // Start Update Positions coroutine StartCoroutine(UpdatePositions()); StartCoroutine(UpdateScale()); StartCoroutine(UpdateColors()); }
// Update 100 random sphere positions private IEnumerator UpdateScale() { while (true) { if (sphereCount > 100 && scaleUpdateFrequency > 0) { Matrix4x4 instance; Vector3 position; Quaternion rotation; Vector3 newScale; // update 100 positions starting from random index int randomIndex = Random.Range(0, sphereCount - 100); for (int i = randomIndex; i < randomIndex + 100; i++) { instance = _matrix4x4Array[i]; position = instance.GetColumn(3); rotation = Quaternion.LookRotation(instance.GetColumn(2), instance.GetColumn(1)); newScale = Vector3.one * Random.Range(0.5f, 1.5f); _matrix4x4Array[i] = Matrix4x4.TRS(position, rotation, newScale); } // set updated transform data GPUInstancerAPI.UpdateVisibilityBufferWithMatrix4x4Array(prefabManager, prefab.prefabPrototype, _matrix4x4Array, randomIndex, randomIndex, 100); } yield return new WaitForSeconds(1 - scaleUpdateFrequency + 0.01f); } }
private IEnumerator AddExtraInstancesAtRuntime() { // Extra instance count that can be added at runtime is limited by the "Extra buffer size" property defined for this prefab prototype in the manager. for (int i = 0; i < prefab.prefabPrototype.extraBufferSize; i++) { GPUInstancerPrefab prefabInstance = Instantiate(prefab); prefabInstance.transform.localPosition = Random.insideUnitSphere * 5; // Move the extra spheres to the outer sphere prefabInstance.transform.localPosition = prefabInstance.transform.localPosition.normalized * (prefabInstance.transform.localPosition.magnitude + 10f); prefabInstance.transform.SetParent(parentTransform); if (!prefabInstance.prefabPrototype.addRuntimeHandlerScript) { GPUInstancerAPI.AddPrefabInstance(prefabManager, prefabInstance); } extraInstancesList.Add(prefabInstance); if (!addRemoveInstantlyToggle.isOn) { yield return(new WaitForSeconds(0.001f)); } } EnableButton("RemoveExtraInstancesButton"); if (instancesList.Count == 0) { EnableButton("AddInstancesButton"); } else { EnableButton("RemoveInstancesButton"); } }
public void ReInitializeManagers() { for (int i = 0; i < terrainCounter; i++) { GPUInstancerDetailManager detailManager = terrainArray[i].GetComponent <GPUInstancerDetailManager>(); GPUInstancerAPI.InitializeGPUInstancer(detailManager); } }
private void Start() { if (prefabManager != null && prefabManager.gameObject.activeSelf && prefabManager.enabled) { GPUInstancerAPI.RegisterPrefabInstanceList(prefabManager, asteroidInstances); GPUInstancerAPI.InitializeGPUInstancer(prefabManager); } }
public void AddSpheres() { int previousSphereCount = sphereCount; AddMatrix4x4ToArray(1000); // UI CheckButtonsAvailablity(); // set updated transform data GPUInstancerAPI.UpdateVisibilityBufferWithMatrix4x4Array(prefabManager, prefab.prefabPrototype, _matrix4x4Array, previousSphereCount, previousSphereCount, 1000); GPUInstancerAPI.SetInstanceCount(prefabManager, prefab.prefabPrototype, sphereCount); }
private void Update() { if (_camera.isActiveAndEnabled && !_isCameraSet) { GPUInstancerAPI.SetCamera(_camera); _isCameraSet = true; } else if (!_camera.isActiveAndEnabled && _isCameraSet) { _isCameraSet = false; } }
private void SetCameraMode(CameraModes cameraMode) { if (!fpController || !spaceshipCamera || !grassMowerCamera) { Debug.Log("Not all cameras are set. Please assign the relevant cameras from the inspector"); return; } fpController.SetActive(false); spaceshipCamera.SetActive(false); grassMowerCamera.SetActive(false); _spaceShip.GetComponent <SpaceshipController>().enabled = false; _spaceShipThrusterGlow.gameObject.SetActive(false); _spaceShipControlsText.gameObject.SetActive(false); _grassMower.GetComponent <GrassMowerController>().enabled = false; _grassMower.GetComponent <GPUInstancerInstanceRemover>().enabled = false; _grassMowerControlsText.gameObject.SetActive(false); switch (cameraMode) { case CameraModes.FPMode: fpController.SetActive(true); _activeCameraGO = fpController; break; case CameraModes.SpaceshipMode: spaceshipCamera.SetActive(true); _spaceShip.GetComponent <SpaceshipController>().enabled = true; _spaceShipThrusterGlow.gameObject.SetActive(true); _spaceShipControlsText.gameObject.SetActive(true); _activeCameraGO = spaceshipCamera; break; case CameraModes.MowerMode: grassMowerCamera.SetActive(true); _grassMower.GetComponent <GrassMowerController>().enabled = true; _grassMower.GetComponent <GPUInstancerInstanceRemover>().enabled = true; _grassMowerControlsText.gameObject.SetActive(true); _activeCameraGO = grassMowerCamera; break; } _currentCameraMode = cameraMode; // Notify GPU Instancer of the camera change: GPUInstancerAPI.SetCamera(_activeCameraGO.GetComponentInChildren <Camera>()); }
void Update() { if (transform.hasChanged && transform.position != _previousPosition) { foreach (GPUInstancerManager manager in gPUIManagers) { if (manager != null) { GPUInstancerAPI.SetGlobalPositionOffset(manager, transform.position - _previousPosition); } } _previousPosition = transform.position; transform.hasChanged = false; } }
// Update 100 random sphere positions private IEnumerator UpdateColors() { while (true) { if (sphereCount > 100 && colorUpdateFrequency > 0) { // update 100 positions starting from random index int randomIndex = Random.Range(0, sphereCount - 100); for (int i = randomIndex; i < randomIndex + 100; i++) variationData[i] = Random.ColorHSV(); // set updated transform data GPUInstancerAPI.UpdateVariationFromArray(prefabManager, prefab.prefabPrototype, bufferName, variationData, randomIndex, randomIndex, 100); } yield return new WaitForSeconds(1 - colorUpdateFrequency + 0.01f); } }
private void Update() { if (Input.GetKeyUp(KeyCode.C)) { SwitchCameraMode(); } if (Input.GetKeyUp(KeyCode.U)) { _uiCanvas.gameObject.SetActive(!_uiCanvas.gameObject.activeSelf); } if (Input.GetKeyUp(KeyCode.F1)) { if (detailManager.gameObject.activeSelf && persistRemoval) { detailMapData = GPUInstancerAPI.GetDetailMapData(detailManager); } detailManager.gameObject.SetActive(!detailManager.gameObject.activeSelf); if (detailManager.gameObject.activeSelf) { if (persistRemoval && detailMapData != null) { GPUInstancerAPI.SetDetailMapData(detailManager, detailMapData); } _loadingTerrainDetailsText.SetActive(true); GPUInstancerAPI.SetCamera(_activeCameraGO.GetComponentInChildren <Camera>()); GPUInstancerAPI.StartListeningGPUIEvent(GPUInstancerEventType.DetailInitializationFinished, DisableLoadingTerrainDetailsText); } SetQualityMode(_currentQualityMode); } if (Input.GetKeyUp(KeyCode.F2)) { SetQualityMode(QualityMode.Low); } if (Input.GetKeyUp(KeyCode.F3)) { SetQualityMode(QualityMode.Mid); } if (Input.GetKeyUp(KeyCode.F4)) { SetQualityMode(QualityMode.High); } }
private void UpdateManagers() { for (int i = 0; i < terrainCounter; i++) { GPUInstancerDetailManager detailManager = terrainArray[i].GetComponent <GPUInstancerDetailManager>(); detailManager.terrainSettings.windVector = _windVector; for (int j = 0; j < detailManager.prototypeList.Count; j++) { GPUInstancerDetailPrototype detailPrototype = (GPUInstancerDetailPrototype)detailManager.prototypeList[j]; // noise settings: detailPrototype.detailHealthyColor = _healthyColor; detailPrototype.detailDryColor = _dryColor; detailPrototype.noiseSpread = _noiseSpread; detailPrototype.ambientOcclusion = _ambientOcclusion; detailPrototype.gradientPower = _gradientPower; // wind settings: detailPrototype.windIdleSway = _windIdleSway; detailPrototype.windWavesOn = _windWavesOn; detailPrototype.windWaveTint = _windWaveTint; detailPrototype.windWaveSize = _windWaveSize; detailPrototype.windWaveSway = _windWaveSway; detailPrototype.windWaveTintColor = _windWaveTintColor; // mesh settings: detailPrototype.isBillboard = _useCrossQuads ? false : _isBillboard; detailPrototype.useCrossQuads = _useCrossQuads; detailPrototype.quadCount = _crossQuadCount; detailPrototype.billboardDistance = _crossQuadBillboardDistance; detailPrototype.detailScale = _scale; // GPU Instancer settings detailPrototype.isShadowCasting = _isShadowCasting; detailPrototype.isFrustumCulling = _isFrustumCulling; detailPrototype.frustumOffset = _frustumOffset; detailPrototype.maxDistance = _maxDistance; } GPUInstancerAPI.UpdateDetailInstances(detailManager, true); } }
// Update 100 random sphere positions private IEnumerator UpdatePositions() { while (true) { if(sphereCount > 100 && positionUpdateFrequency > 0) { Vector3 newPosition; // update 100 positions starting from random index int randomIndex = Random.Range(0, sphereCount - 100); for (int i = randomIndex; i < randomIndex + 100; i++) { newPosition = Random.insideUnitSphere * 20; _matrix4x4Array[i].SetColumn(3, new Vector4(newPosition.x, newPosition.y, newPosition.z, _matrix4x4Array[i][3, 3])); } // set updated transform data GPUInstancerAPI.UpdateVisibilityBufferWithMatrix4x4Array(prefabManager, prefab.prefabPrototype, _matrix4x4Array, randomIndex, randomIndex, 100); } yield return new WaitForSeconds(1 - positionUpdateFrequency + 0.01f); } }
IEnumerator AddRemoveAtRuntime() { while (true) { // Loop through primitives foreach (PrimitiveType primitiveType in Enum.GetValues(typeof(PrimitiveType))) { yield return(new WaitForSeconds(3)); // Remove runtime generated prototype definition GPUInstancerAPI.RemovePrototypeAtRuntime(prefabManager, prototype); // Clear the instances ClearInstances(); yield return(new WaitForSeconds(1)); // Create a GameObject to create a prototype from prototypeGameObject = GameObject.CreatePrimitive(primitiveType); // Set material of the GameObject SetMaterial(); // Add the original to the instanceList instanceList.Add(prototypeGameObject); // Define the prototype prototype = GPUInstancerAPI.DefineGameObjectAsPrefabPrototypeAtRuntime(prefabManager, prototypeGameObject); // Create 1000 new instances for (int i = 0; i < 1000; i++) { instanceList.Add(Instantiate(prototypeGameObject, UnityEngine.Random.insideUnitSphere * 20, Quaternion.identity)); } // Add instances to manager GPUInstancerAPI.AddInstancesToPrefabPrototypeAtRuntime(prefabManager, prototype, instanceList); yield return(new WaitForSeconds(1)); } } }
private void AddInstancer(Terrain terrain) { GPUInstancerDetailManager detailManager = terrain.gameObject.AddComponent <GPUInstancerDetailManager>(); GPUInstancerAPI.SetupManagerWithTerrain(detailManager, terrain); detailManager.terrainSettings.windVector = _windVector; // Can change prototype properties here if (detailManager.prototypeList.Count > 0) { GPUInstancerDetailPrototype detailPrototype = (GPUInstancerDetailPrototype)detailManager.prototypeList[0]; detailPrototype.detailHealthyColor = _healthyColor; detailPrototype.detailDryColor = _dryColor; detailPrototype.noiseSpread = _noiseSpread; detailPrototype.ambientOcclusion = _ambientOcclusion; detailPrototype.gradientPower = _gradientPower; detailPrototype.windIdleSway = _windIdleSway; detailPrototype.windWavesOn = _windWavesOn; detailPrototype.windWaveTint = _windWaveTint; detailPrototype.windWaveSize = _windWaveSize; detailPrototype.windWaveSway = _windWaveSway; detailPrototype.windWaveTintColor = _windWaveTintColor; detailPrototype.isBillboard = _isBillboard; detailPrototype.useCrossQuads = _useCrossQuads; detailPrototype.quadCount = _crossQuadCount; detailPrototype.billboardDistance = _crossQuadBillboardDistance; detailPrototype.detailScale = _scale; detailPrototype.isShadowCasting = _isShadowCasting; detailPrototype.isFrustumCulling = _isFrustumCulling; detailPrototype.frustumOffset = _frustumOffset; detailPrototype.maxDistance = _maxDistance; } GPUInstancerAPI.InitializeGPUInstancer(detailManager); }
private void SetQualityMode(QualityMode qualityMode) { if (!detailManager.gameObject.activeSelf) { _currentQualityModeText.text = "Current Quality Mode: GPU Instancer disabled (Unity terrain)"; } else { _currentQualityModeText.text = "Current Quality Mode: " + qualityMode + " Quality"; if (_currentQualityMode == qualityMode) { return; } _currentQualityMode = qualityMode; SetPrototypesByQuality(qualityMode); GPUInstancerAPI.UpdateDetailInstances(detailManager, true); } }
private void Start() { foreach (GPUInstancerManager manager in GPUInstancerManager.activeManagerList) { if ((!removeFromDetailManagers && manager is GPUInstancerDetailManager) || (!removeFromTreeManagers && manager is GPUInstancerTreeManager) || (!removeFromPrefabManagers && manager is GPUInstancerPrefabManager)) { continue; } //GPUInstancerAPI.InitializeGPUInstancer(manager, false); foreach (Collider collider in selectedColliders) { if (useBounds) { GPUInstancerAPI.RemoveInstancesInsideBounds(manager, collider.bounds, offset, onlyRemoveSelectedPrototypes ? selectedPrototypes : null); } else { GPUInstancerAPI.RemoveInstancesInsideCollider(manager, collider, offset, onlyRemoveSelectedPrototypes ? selectedPrototypes : null); } } } }
private void SwitchCameras() { if (!FpsController || !FixedCamera) { return; } FpsController.SetActive(isCurrentCameraFixed); FixedCamera.SetActive(!isCurrentCameraFixed); var managers = FindObjectsOfType <GPUInstancerDetailManager>(); foreach (var manager in managers) { GPUInstancerAPI.SetCamera(isCurrentCameraFixed ? FpsController.GetComponentInChildren <Camera>() : FixedCamera.GetComponentInChildren <Camera>()); } if (!isCurrentCameraFixed) { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } }
private void DisableLoadingTerrainDetailsText() { _loadingTerrainDetailsText.SetActive(false); GPUInstancerAPI.StopListeningGPUIEvent(GPUInstancerEventType.DetailInitializationFinished, DisableLoadingTerrainDetailsText); }
public void SetCamera(Camera camera) { cameraData.mainCamera = camera; GPUInstancerAPI.SetCamera(camera); }
void Update() { // Update the variation buffer with a random set of colors every frame, thus changing instance colors per instance every frame. GPUInstancerAPI.UpdateVariation(prefabManager, goList[Random.Range(0, goList.Count)], bufferName, (Vector4)Random.ColorHSV()); }