using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
//obj data class(위치, 크기, 회전값)
public class ObjData
{
public Vector3 pos;
public Vector3 scale;
public Quaternion rot;
//위치, 회전, 크기에 대한 정보 행렬 가져오기
public Matrix4x4 matrix
{
get
{
return Matrix4x4.TRS(pos, rot, scale);
}
}
//현재 위치 저장
public ObjData(Vector3 pos, Vector3 scale, Quaternion rot)
{
this.pos = pos;
this.scale = scale;
this.rot = rot;
}
}
//생성자 class
public class Spawner : MonoBehaviour
{
public int instances; // obj 생성 개수
public Vector3 maxPos; // 생성 박스의 크기
public Mesh[] objMeshes; // obj의 형태
public Material[] objMats; // obj의 매트리얼
//batch 리스트
private List<List<ObjData>> batches = new List<List<ObjData>>();
private List<int> MeshList = new List<int>();
private List<int> MatList = new List<int>();
void Start()
{
int batchIndexNum = 0;
//현재 objdata 리스트를 새로운 objdata리스트에 저장
List<ObjData> currBatch = new List<ObjData>();
for(int i=0; i<instances; i++)
{
AddObj(currBatch, i); //objData리스트 넘버링
//objData리스트의 형태 : [currBatch, 1], [currBatch, 2]...
batchIndexNum++;
//batchIndexNum이 1000을 주기로 batches리스트에 새로운 objData 리스트를 추가
//(리스트의 열이 늘어나는 것으로 생각)
if(batchIndexNum >= 1000)
{
batches.Add(currBatch);
currBatch = BuiildNewBatch();
batchIndexNum = 0;
}
}
for(int i=0; i<batches.Count; i++)
{
int objMeshIndex = Random.Range(0, objMeshes.Length);
int objMatIndex = Random.Range(0, objMats.Length);
MeshList.Add(objMeshIndex);
MatList.Add(objMatIndex);
}
}
void Update()
{
RenderBatches();
}
//위치 지정
private void AddObj(List<ObjData> currBatch, int i)
{
Vector3 position = new Vector3(Random.Range(-maxPos.x, maxPos.x), Random.Range(-maxPos.y, maxPos.y), Random.Range(-maxPos.z, maxPos.z));
currBatch.Add(new ObjData(position, new Vector3(2, 2, 2), Quaternion.identity));
}
private List<ObjData> BuiildNewBatch()
{
return new List<ObjData>();
}
//object를 그리는
private void RenderBatches()
{
//fixed
//for(int i=0; i<batches.Count; i++)
//{
// Graphics.DrawMeshInstanced(objMeshes[MeshList[i]], 0, objMats[MatList[i]], batches[i].Select((a) => a.matrix).ToList());
// //batches[i] 즉, batch 안에 있는 원소들을 개별적으로 선택해서 matrix연산(matrix행렬로 변환)을 적용시킨 후, list로 변환.
//}
//random
foreach(var batch in batches)
{
Graphics.DrawMeshInstanced(objMeshes[Random.Range(0, objMeshes.Length)], 0, objMats[Random.Range(0, objMats.Length)], batch.Select((a) => a.matrix).ToList());
}
}
}