Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Net;
- using System.Net.Sockets;
- using System.IO;
- using System;
- using System.Text;
- using System.Threading;
- using UnityEngine;
- using System.Collections;
- /**
- * <summary>
- * Класс космического зонда
- * </summary>
- * */
- public class SpaceShip
- {
- private GameObject ship = GameObject.Find("Cube");;
- public SpaceShip()
- {
- }
- public void UpatePosition(float x, float y, float z)
- {
- ship.transform.position = new Vector3(x, y, z);
- }
- public void UpdateRotation(float a, float b, float g)
- {
- ship.transform.rotation = Quaternion.Euler(a, b, g);
- }
- public Transform GetTransform()
- {
- return ship.transform;
- }
- }
- /**
- * <summary>
- * TCP-сервер, ожидает подключение единственного клиента. Запусткается в
- * отдельном потоке.
- * </summary>
- * */
- public class ServerTCP {
- IPAddress Ip = IPAddress.Parse("127.0.0.1");
- int Port = 9090;
- NetworkStream Stream;
- TcpListener Server;
- TcpClient Client;
- Boolean Ready = false;
- float[] Data = new float[6];
- Thread thread;
- public ServerTCP() {
- thread = new Thread ( () => {
- try {
- Server = new TcpListener (Ip, Port);
- Server.Start();
- Debug.Log("Ожидание подключений... ");
- Client = Server.AcceptTcpClient();
- Debug.Log("Подключен клиент.");
- Stream = Client.GetStream();
- Ready = true;
- while(true) {
- Read();
- }
- } catch (Exception e)
- {
- Debug.Log("Socket error: " + e);
- }
- });
- thread.Start ();
- }
- public Boolean IsReady() {
- return Ready;
- }
- public float[] GetData() {
- return Data;
- }
- public void Close() {
- thread.Abort ();
- if (Stream != null) {
- Stream.Close ();
- }
- if (Client != null) {
- Client.Close ();
- }
- if (Server != null) {
- Server.Stop ();
- }
- }
- void Read()
- {
- Byte[] bytes = new Byte[4];
- for (int i = 0; i < 6; ++i) {
- Stream.Read (bytes, 0, 4);
- Data[i] = BitConverter.ToSingle(bytes, 0);
- //Debug.Log(data[i]);
- }
- }
- }
- /**
- * <summary>
- * Базовый класс переключаемых камер. Паттерн "Состояние".
- * </summary>
- * */
- public class CameraBase {
- protected Camera C;
- protected GameObject Ship = GameObject.Find("Cube");
- protected CameraBase (string CameraName) {
- C = GameObject.Find(CameraName).GetComponent<Camera>();
- }
- public void Activate() {
- C.gameObject.SetActive (true);
- }
- public void Deactivate() {
- C.gameObject.SetActive (false);
- }
- public virtual void Update() {
- }
- }
- /**
- * <summary>
- * Камера, находящая позади космического зонда
- * </summary>
- * */
- public class CameraBack: CameraBase {
- public CameraBack(): base("Main Camera") {
- C.transform.SetParent (Ship.transform);
- }
- }
- /**
- * <summary>
- * Камера, находящая на носу космического зонда
- * </summary>
- * */
- public class CameraForvard: CameraBase {
- public CameraForvard(): base("Main Camera (1)") {
- C.transform.SetParent (Ship.transform);
- }
- }
- /**
- * <summary>
- * Камера, обеспечивающая свободный полет
- * </summary>
- * */
- public class CameraFly: CameraBase {
- float mouseSensitivity = 3.0f;
- float speed = 15.0f;
- Vector3 transfer;
- float minimumX = -360F;
- float maximumX = 360F;
- float minimumY = -60F;
- float maximumY = 60F;
- float rotationX = 0F;
- float rotationY = 0F;
- Quaternion originalRotation;
- public CameraFly(): base("CameraFly") {
- originalRotation = C.transform.rotation;
- }
- public override void Update() {
- rotationX += Input.GetAxis("Mouse X") * mouseSensitivity;
- rotationY += Input.GetAxis("Mouse Y") * mouseSensitivity;
- rotationX = ClampAngle (rotationX, minimumX, maximumX);
- rotationY = ClampAngle (rotationY, minimumY, maximumY);
- Quaternion xQ = Quaternion.AngleAxis (rotationX, Vector3.up);
- Quaternion yQ = Quaternion.AngleAxis (rotationY, Vector3.left);
- C.transform.rotation = originalRotation * xQ * yQ;
- // перемещение камеры
- transfer = C.transform.forward * Input.GetAxis("Vertical");
- transfer += C.transform.right * Input.GetAxis("Horizontal");
- C.transform.position += transfer * speed * Time.deltaTime;
- }
- public float ClampAngle (float angle, float min, float max)
- {
- if (angle < -360F) angle += 360F;
- if (angle > 360F) angle -= 360F;
- return Mathf.Clamp (angle, min, max);
- }
- }
- /**
- * <summary>
- * Камера, которая будет получать изображение, которое в дальнейшем должно быть
- * обработано
- * </summary>
- * */
- public class CameraView {
- protected Camera C = GameObject.Find("CameraView").GetComponent<Camera>();
- protected GameObject Ship = GameObject.Find("Cube");
- public CameraView() {
- C.transform.SetParent (Ship.transform);
- }
- public Texture2D getTexture () {
- RenderTexture currentRT = RenderTexture.active;
- RenderTexture.active = C.targetTexture;
- C.Render();
- Texture2D image = new Texture2D(C.targetTexture.width, C.targetTexture.height);
- image.ReadPixels(new Rect(0, 0, C.targetTexture.width, C.targetTexture.height), 0, 0);
- image.Apply();
- RenderTexture.active = currentRT;
- Debug.Log (image.EncodeToJPG().Length);
- return image;
- }
- }
- /**
- * <summary>
- * Класс-менеджер камер
- * </summary>
- * */
- public class CamarasManager {
- CameraBase CurrentCamera;
- CameraBack CBack = new CameraBack();
- CameraForvard CForvard = new CameraForvard ();
- CameraView CView = new CameraView();
- CameraFly CFly = new CameraFly();
- public CamarasManager() {
- CForvard.Deactivate ();
- CFly.Deactivate ();
- CurrentCamera = CBack;
- getTexture ();
- }
- public void Update () {
- if (Input.GetKeyUp(KeyCode.Alpha1) && CurrentCamera != CBack) {
- CurrentCamera.Deactivate ();
- CurrentCamera = CBack;
- CurrentCamera.Activate ();
- } else if (Input.GetKeyUp(KeyCode.Alpha2) && CurrentCamera != CForvard ) {
- CurrentCamera.Deactivate ();
- CurrentCamera = CForvard ;
- CurrentCamera.Activate ();
- } else if (Input.GetKeyUp(KeyCode.Alpha3) && CurrentCamera != CFly ) {
- CurrentCamera.Deactivate ();
- CurrentCamera = CFly;
- CurrentCamera.Activate ();
- }
- CurrentCamera.Update ();
- //getTexture ();
- }
- public Texture2D getTexture () {
- return CView.getTexture ();
- }
- }
- public class test_1 : MonoBehaviour {
- ServerTCP Server;
- SpaceShip Ship;
- GameObject Particle;
- CamarasManager CM;
- float x, y, z, a, b, g;
- void Start () {
- Server = new ServerTCP();
- Ship = new SpaceShip();
- Particle = GameObject.Find("Particle System");
- CM = new CamarasManager ();
- }
- void OnGUI() {
- GUI.Label(new Rect(30, 30, 400, 60), "Для переключения камер используйте клавиши 1, 2, 3.\n" +
- "Для Камеры 3 доступен свободный полет (WASD + мышь).");
- Color c = GUI.color;
- if (Server.IsReady () ) {
- GUI.color = Color.green;
- GUI.Label(new Rect(30, 80, 400, 50), "Соединение с TCP-клиентом Simulink установлено");
- } else {
- GUI.color = Color.red;
- GUI.Label(new Rect(30, 80, 200, 30), "Ожидание подключения simulink");
- }
- GUI.color = c;
- }
- void Update () {
- if (Server.IsReady ()) {
- float[] data = Server.GetData ();
- x = data [0];
- y = data [1];
- z = data [2];
- a = data [3];
- b = data [4];
- g = data [5];
- Ship.UpatePosition (x, y, z);
- Ship.UpdateRotation (a, b, g);
- Particle.transform.position = new Vector3 (x - 2f, y, z - 0.75f);
- }
- CM.Update ();
- }
- void OnApplicationQuit() {
- Server.Close ();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement