Tanoda
TestScript.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Linq;
4using System.Collections.Generic;
5using System.IO;
6using System.Runtime.InteropServices;
7using System.Text;
8//using System.Net;
9using System.Threading;
10using Es.InkPainter;
11using GILES;
12using GILES.Interface;
14using NaughtyAttributes;
15using Newtonsoft.Json;
16#if UNITY_EDITOR
17using UnityEditor;
18#endif
19using UnityEngine;
20using HybridWebSocket;
21using UnityEngine.Video;
22using WebSocketSharp;
23using WebSocketSharp.Server;
24using ErrorEventArgs = WebSocketSharp.ErrorEventArgs;
25#if !UNITY_WEBGL
26using System.Drawing;
27using System.Drawing.Imaging;
28#endif
29using System.IO;
30using System.Runtime.InteropServices;
31using Random = UnityEngine.Random;
32using Color = UnityEngine.Color;
34using UnityEngine.UI;
35
36#if !UNITY_WEBGL
37using Image = System.Drawing.Image;
38#endif
39
40public class TestScript : MonoBehaviour
41{
42#if UNITY_WEBGL
43 [DllImport("__Internal")]
44 private static extern void GetUrlFromIndexedDB(string file, string dbName, string otherName);
45
46 [DllImport("__Internal")]
47 private static extern void syncfs();
48
49 IEnumerator Start()
50 {
51 yield return new WaitForSeconds(2);
52 //syncfs();
53 //
54 //yield return new WaitForSeconds(5);
55 //GetUrlFromIndexedDB("RL_720.mp4", "/idbfs", "FILE_DATA");
56
57 //StartCoroutine(worker());
58
59 //Debug.Log ("Server Started");
60
61 }
62 public void GetUrlFromWebGL(string value)
63 {
64 var url = value.Split(';')[0];
65 var filePath = value.Split(';')[1];
66 Debug.Log("GetUrlFromWebGL: URL: " + url);
67 Debug.Log("GetUrlFromWebGL: URL filePath : " + filePath);
68 try
69 {
70 FileDragAndDrop.instance.paretnObject.transform.GetComponentInChildren<VideoPlayer>().url = url;
71 }
72 catch (Exception e)
73 {
74 Debug.Log(e);
75 StartCoroutine(worker(url));
76 }
77
78 }
79#endif
80
81 public Transform fromRot, toRot;
82
83 public Texture2D toPng;
84
85 [Button] void convertPic()
86 {
87 File.WriteAllBytes("export.png", DeCompress(toPng).EncodeToPNG());
88 }
89 public Texture2D DeCompress(Texture2D source)
90 {
91 RenderTexture renderTex = RenderTexture.GetTemporary(
92 source.width,
93 source.height,
94 0,
95 RenderTextureFormat.Default,
96 RenderTextureReadWrite.Linear);
97
98 UnityEngine.Graphics.Blit(source, renderTex);
99 RenderTexture previous = RenderTexture.active;
100 RenderTexture.active = renderTex;
101 Texture2D readableText = new Texture2D(source.width, source.height);
102 readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
103 readableText.Apply();
104 RenderTexture.active = previous;
105 RenderTexture.ReleaseTemporary(renderTex);
106 return readableText;
107 }
108 [Button]
109 private void tesztRotate()
110 {
111 toRot.forward = fromRot.forward;
112 toRot.right = fromRot.right;
113 toRot.up = fromRot.up;
114 }
115
116 [Button]
117 private void extensions()
118 {
119 Debug.Log(Path.GetExtension("asd.fbx"));
120 Debug.Log(Path.GetExtension("asd.FBX"));
121 Debug.Log(Path.GetExtension("asd"));
122 Debug.Log(Path.GetExtension("asd.tar.gz"));
123 Debug.Log(Path.GetExtension("asd.FBX (Clone)"));
124 }
125
126 [Button]
127 private void shaderChanger()
128 {
129 ShaderChanger.Change(GetComponentsInChildren<MeshRenderer>(), "Ciconia Studio/Double Sided/Standard/Diffuse Bump");
130 }
131
132 [Button]
133 private void Teszt69()
134 {
135 StartCoroutine(FollowHand());
136 }
137
138 public GameObject hand, from, to, moveItem;
139 private IEnumerator FollowHand()
140 {
141 Vector3 targetWorldPos = to.transform.position;
142 //if (targetPosition != originalPosition)
143 {
144 while (Mathf.Abs(Vector3.Distance(moveItem.transform.position, targetWorldPos)) > 0.02)
145 {
146 var handdistance = Vector3.Distance(hand.transform.position, from.transform.position);
147 var dist = Vector3.Distance(from.transform.position, to.transform.position);
148 var percent = handdistance / dist;
149
150 moveItem.transform.localPosition = Vector3.Lerp(from.transform.position, to.transform.position, percent);
151 moveItem.transform.localEulerAngles = Vector3.Lerp(Macro.ClampAngle(from.transform.eulerAngles),
152 Macro.ClampAngle(to.transform.eulerAngles), percent);
153 yield return null;
154 }
155 }
156
157 moveItem.transform.SetParent(null, true);
158
159 }
160
161 private IEnumerator FollowHandRot()
162 {
163 var target = Quaternion.Angle(Quaternion.Euler(from.transform.eulerAngles), Quaternion.Euler(to.transform.eulerAngles));
164 var current = Quaternion.Angle(Quaternion.Euler(from.transform.eulerAngles), moveItem.transform.rotation);
165
166 GameObject helper = new GameObject();
167 helper.transform.position = moveItem.transform.position;
168 helper.transform.rotation = moveItem.transform.rotation;
169
170 while (Mathf.Abs(target - current) > 1) //TODO offsetholderer positionból számítás
171 {
172 helper.transform.LookAt(hand.transform);
173 current = Quaternion.Angle(Quaternion.Euler(from.transform.eulerAngles), helper.transform.rotation);
174
175 var percent = current / target;
176 moveItem.transform.localPosition = Vector3.Lerp(from.transform.position, to.transform.position, percent);
177 moveItem.transform.localEulerAngles = Vector3.Lerp(Macro.ClampAngle(from.transform.eulerAngles),
178 Macro.ClampAngle(to.transform.eulerAngles), percent);
179
180 yield return null;
181 }
182
183 }
184
185 private IEnumerator worker(string url)
186 {
187
188 yield return new WaitForSeconds(5);
189 FileDragAndDrop.instance.paretnObject.transform.GetComponentInChildren<VideoPlayer>().url = url;
190 }
191
192#if UNITY_EDITOR
193 [Range(0,1)] public float percent = 0;
194
195 [MenuItem("Edit/Cleanup Missing Scripts")]
196 static void CleanupMissingScripts ()
197 {
198 for(int i = 0; i < Selection.gameObjects.Length; i++)
199 {
200 var gameObject = Selection.gameObjects[i];
201 for (int j = 0; j < gameObject.transform.childCount; j++)
202 {
203 CleanupMissingScripts(gameObject.transform.GetChild(j).gameObject);
204 }
205 GameObjectUtility.RemoveMonoBehavioursWithMissingScript(gameObject);
206 continue;
207 // We must use the GetComponents array to actually detect missing components
208 var components = gameObject.GetComponents<Component>();
209
210 // Create a serialized object so that we can edit the component list
211 var serializedObject = new SerializedObject(gameObject);
212 // Find the component list property
213 var prop = serializedObject.FindProperty("m_Component");
214
215 // Track how many components we've removed
216 int r = 0;
217
218 // Iterate over all components
219 for(int j = 0; j < components.Length; j++)
220 {
221 // Check if the ref is null
222 if(components[j] == null)
223 {
224 // If so, remove from the serialized component array
225 prop.DeleteArrayElementAtIndex(j-r);
226 // Increment removed count
227 r++;
228 }
229 }
230
231 // Apply our changes to the game object
232 serializedObject.ApplyModifiedProperties();
233 }
234 }
235
236 static void CleanupMissingScripts(GameObject go)
237 {
238 GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
239 for (int j = 0; j < go.transform.childCount; j++)
240 {
241 CleanupMissingScripts(go.transform.GetChild(j).gameObject);
242 }
243 }
244
245 [Button]
246 void FastReload()
247 {
248 HashingManager.instance.ClearHashTable();
249 pb_Scene.instance.Clear();
250 pb_Hierarchy.instance.RebuildInspector();
252 PanoramaManager.instance.ClearImage();
253
254 pb_Scene.instance.currentLevelName = LevelEditorOnLoaded.instance.lastLoadedName;
255 pb_Scene.LoadLevel(LevelEditorOnLoaded.instance.lastLoadedJson, true);
256 }
257
258 [Button]
259 void SerializeStageManager()
260 {
261 string scenegraph = JsonConvert.SerializeObject(GameObject.FindObjectOfType(typeof(ActionObject)),
262 Formatting.Indented,
263 pb_Serialization.ConverterSettings);
264 Debug.Log(scenegraph);
265 }
266
267 [Button]
268 void SerializeController()
269 {
270 string scenegraph = JsonConvert.SerializeObject(Controller.Instance,
271 Formatting.Indented,
272 pb_Serialization.ConverterSettings);
273 Debug.Log(scenegraph);
274 File.WriteAllText("E:\\teszt.json", scenegraph);
275 }
276
277 [Button]
278 void SerializeLineDrawer()
279 {
280 string scenegraph = JsonConvert.SerializeObject(LineDrawer.Instance,
281 Formatting.Indented,
282 pb_Serialization.ConverterSettings);
283 Debug.Log(scenegraph);
284 }
285
286 [Button]
287 void DeserializeConnections()
288 {
289 StartCoroutine(Controller.Instance.LoadControllerFromJSON((Controller) JsonConvert.DeserializeObject<Controller>(File.ReadAllText("E:\\teszt.json"), pb_Serialization.ConverterSettings)));
290 }
291
292 public Transform a, b, c;
293
294 //private void Update()
295 //{
296 // c.position = a.position * percent + b.position * (1 - percent);
297 //}
298
299 //void Start()
300 //{
301 // StartCoroutine(A());
302 //}
303 //
304 //IEnumerator A()
305 //{
306 // Debug.Log("A");
307 // yield return B();
308 // Debug.Log("A");
309 //}
310 //IEnumerator B()
311 //{
312 // Debug.Log("B");
313 // yield return new WaitForSeconds(1);
314 // Debug.Log("B");
315 //}
316
317 Vector3 PredictProjectileMovement(Vector3 InitialPosition, Vector3 InitialVelocity, float PredictTime)
318 {
319 float Restitution = 0.5f;
320 Vector3 Position = InitialPosition;
321 Vector3 Velocity = InitialVelocity;
322 Vector3 GravitationalAcceleration = new Vector3(0.0f, 0.0f, 0.0f);/* = new Vector3(0.0f, -9.81f, 0.0f);*/
323 float t = 0.0f;
324 float DeltaTime = Time.deltaTime;
325
326 while (t < PredictTime)
327 {
328 //Vector3 PreviousPosition = Position;
329 //Vector3 PreviousVelocity = Velocity;
330
331 Position += Velocity * DeltaTime /*+ 0.5f * GravitationalAcceleration * DeltaTime * DeltaTime*/;
332 //Velocity += GravitationalAcceleration * DeltaTime;
333
334 // Collision detection.
335 //if (Physics.Linecast(PreviousPosition, Position, out var hitInfo))
336 //{
337 // // Recompute velocity at the collision point.
338 // float FullDistance = (Position - PreviousPosition).magnitude;
339 // float HitCoef = (FullDistance > 0.000001f) ? (hitInfo.distance / FullDistance) : 0.0f;
340 // Velocity = PreviousVelocity + GravitationalAcceleration * DeltaTime * HitCoef;
341 //
342 // // Set the hit point as the new position.
343 // Position = hitInfo.point;
344 //
345 // // Collision response. Bounce velocity after the impact using coefficient of restitution.
346 // float ProjectedVelocity = Vector3.Dot(hitInfo.normal, Velocity);
347 // Velocity += -(1+Restitution) * ProjectedVelocity * hitInfo.normal;
348 //}
349
350 t += DeltaTime;
351 }
352
353 // Return the final predicted position.
354 return Position;
355 }
356
357 Vector3 Velocity = Vector3.zero;
358 Vector3 lastPos = Vector3.zero;
359 List<Vector3> lastFewPos = new List<Vector3>();
360 public bool useAvarageVelocity = true;
361 public int avaragePoolSize = 20;
362
363 public static TestScript instance;
364
365 public List<string> allname = new List<string>();
366
367 private void Awake()
368 {
369 instance = this;
370 lastPos = transform.position;
371 foreach (string arg in Environment.GetCommandLineArgs())
372 {
373 Debug.Log(arg);
374 }
375 }
376
377 [Button]
378 void ripList()
379 {
380 File.WriteAllLines("E:\\riplist.txt", allname);
381 }
382
383 public UnityEngine.UI.Text textUI;
384 private void Update()
385 {
386 if (textUI != null)
387 textUI.text = Quaternion.Angle(from.transform.rotation, to.transform.rotation).ToString();
388 return;
389 //if (Input.GetMouseButton(0))
390 //{
391 PointerEventData pointer = new PointerEventData(EventSystem.current);
392 pointer.position = Input.mousePosition;
393
394 List<RaycastResult> raycastResults = new List<RaycastResult>();
395 EventSystem.current.RaycastAll(pointer, raycastResults);
396
397 if (raycastResults.Count > 0)
398 {
399 foreach (var go in raycastResults)
400 {
401 Debug.Log(go.gameObject.name, go.gameObject);
402 }
403 }
404 //}
405 Debug.Log(EventSystem.current.IsPointerOverGameObject());
406#if DANA
407 if (targetObject)
408 GetUVPos();
409 return;
410#endif
411 if (useAvarageVelocity)
412 {
413 lastFewPos.Add(transform.position);
414 if (lastFewPos.Count < 10) return;
415 while (lastFewPos.Count > avaragePoolSize)
416 {
417 lastFewPos.RemoveAt(0);
418 }
419
420 var velocity = Vector3.zero;
421 for (int i = 1; i < lastFewPos.Count; i++)
422 {
423 velocity += lastFewPos[i] - lastFewPos[i - 1];
424 }
425
426 velocity /= lastFewPos.Count;
427
428 Velocity = velocity;
429 }
430 else
431 {
432 Velocity = transform.position - lastPos;
433 lastPos = transform.position;
434 }
435 }
436
437 void OnDrawGizmos()
438 {
439 Gizmos.color = UnityEngine.Color.cyan;
440 Gizmos.DrawWireSphere(PredictMovement(transform, 20), 0.1f);
441 }
442
443 public Vector3 PredictMovement(Transform t, int frames)
444 {
445 //float DeltaTime = Time.deltaTime;
446 Vector3 Position = t.position;
447
448 for (int i = 0; i < frames; i++)
449 {
450 Position += Velocity;
451 //Velocity -= Velocity * rb.drag;
452 }
453
454 return Position;
455 }
456
457 public ActionObject[] aos;
458 [Button]
459 void TESZT()
460 {
461 var egy = GameObject.Find("1");
462 var ketto = GameObject.Find("2");
463 var b1 = Macro.GetBounds(egy);
464 var b2 = Macro.GetBounds(ketto);
465 Debug.Log("b1: " + b1.size);
466 Debug.Log("b2: " + b2.size);
467 return;
468 var controller = JsonConvert.DeserializeObject<Controller>(System.IO.File.ReadAllText(@"D:\controller.json"));
469 return;
470 var asd = JsonConvert.SerializeObject(aos, Formatting.Indented, pb_Serialization.ConverterSettings);
471 Debug.Log(asd);
472 var dsa = JsonConvert.DeserializeObject<ActionObject[]>(asd, pb_Serialization.ConverterSettings);
473 Debug.Log("success");
474 }
475 [Button]
476 void TESZT2()
477 {
478 pb_SceneNode rootNode = new pb_SceneNode(pb_Scene.instance.gameObject);
479 string scenegraph = JsonConvert.SerializeObject(rootNode,
480 Formatting.Indented,
481 pb_Serialization.ConverterSettings);
482 pb_SceneNode root_node = (pb_SceneNode) JsonConvert.DeserializeObject<pb_SceneNode>(scenegraph, pb_Serialization.ConverterSettings);
483 }
484
485 [Button]
486 void TESZT3()
487 {
488 var inkCanvas = gameObject.AddComponent<InkCanvas>();
489 }
490
491 public UnityEngine.UI.RawImage rawImage;
492 [DllImport("user32.dll")]
493 static extern IntPtr GetForegroundWindow();
494
495#if !UNITY_WEBGL
496
497 [Button]
498 void TESZT4()
499 {
500 var hWnd =
501#if UNITY_EDITOR
502 GetForegroundWindow();
503#else
504 FindWindow("UnityWndClass", "VR Skills Toolkit");
505#endif
506 var bmp = CaptureWindow(hWnd);
507 MemoryStream msFinger = new MemoryStream();
508 bmp.Save(msFinger, ImageFormat.Png);
509
510 var t2d = new Texture2D(100, 100, TextureFormat.RGB24, false);
511
512 t2d.LoadImage(msFinger.ToArray());
513
514
515 rawImage.texture = t2d;
516
517
518 }
519#endif
520#if DANA
521 [Button]
522 void ListVoices()
523 {
524 var voices = VoiceTTS.InstalledLanguages();
525 foreach (var voice in voices)
526 {
527 Debug.Log(voice);
528 }
529 }
530
531 [Button]
532 void TTSInitialize()
533 {
534 VoiceTTS.Initialize();
535 }
536
537 [Button]
538 void GetAllSameLength()
539 {
540 sameLength.Clear();
541 colors.Clear();
542 var mesh = GetComponent<MeshFilter>().mesh;
543 var verts = mesh.vertices;
544 var tri = mesh.triangles;
545 var percent = mesh.bounds.size / 100;
546 var maxlength = Mathf.Sqrt(Mathf.Pow(percent.x * 5, 2) + Mathf.Pow(percent.y * 5, 2) + Mathf.Pow(percent.z * 5, 2));
547 foreach (var v1 in verts)
548 {
549 foreach (var v2 in verts)
550 {
551 //for (int j = 0; j < verts.Length - 1; j++)
552 //{
553 // {
554 // var v1 = verts[j];
555 // var v2 = verts[j + 1];
556
557
558 if (v1 == v2) continue;
559
560 var dist = Vector3.Distance(v1, v2);
561 if (dist > maxlength) continue;
562
563 bool ok = false;
564 for (int i = 0; i < tri.Length - 2; i += 3)
565 {
566 List<Vector3> v = new List<Vector3>() { verts[tri[i]], verts[tri[i + 1]], verts[tri[i + 2]] };
567 if (v.Contains(v1) && v.Contains(v2))
568 {
569 ok = true;
570 break;
571 }
572 }
573 if (!ok) continue;
574
575 if (!sameLength.ContainsKey(dist))
576 {
577 sameLength.Add(dist, new List<Vector3>() { v1, v2 });
578 }
579 else
580 {
581 sameLength[dist].Add(v1);
582 sameLength[dist].Add(v2);
583 }
584 }
585 }
586
587 Debug.Log($"num of diff lenghts b4 merge: {sameLength.Count}");
588
589 var mergedDict = new SortedDictionary<float, List<Vector3>>();
590 var prevKey = 0f;
591 var usingKey = 0f;
592 var mergeMaxDiff = (percent / 100).magnitude;
593
594 foreach (var kv in sameLength)
595 {
596 if (prevKey == 0)
597 {
598 prevKey = kv.Key;
599 usingKey = kv.Key;
600 mergedDict.Add(kv.Key, kv.Value);
601 continue;
602 }
603 if (Mathf.Abs(prevKey - kv.Key) < mergeMaxDiff)
604 {
605 mergedDict[usingKey].AddRange(kv.Value);
606 }
607 else
608 {
609 usingKey = kv.Key;
610 mergedDict.Add(kv.Key, kv.Value);
611 }
612 prevKey = kv.Key;
613 }
614 Debug.Log($"num of diff lenghts after merge: {mergedDict.Count}");
615
616 sameLength.Clear();
617 sameLength = mergedDict;
618
619 for (int i = 0; i < sameLength.Count; i++)
620 {
621 colors.Add(new Color(Random.value, Random.value, Random.value));
622 }
623 }
624
625 [Button]
626 void GetAllSameLengthButCooler() => StartCoroutine(DontDiePls());
627
628 IEnumerator DontDiePls()
629 {
630
631 sameLength.Clear();
632 colors.Clear();
633 var mesh = GetComponent<MeshFilter>().mesh;
634 var verts = mesh.vertices;
635 var tri = mesh.triangles;
636 var percent = mesh.bounds.size / 100;
637 var maxlength = Mathf.Sqrt(Mathf.Pow(percent.x * 5, 2) + Mathf.Pow(percent.y * 5, 2) + Mathf.Pow(percent.z * 5, 2));
638 int k = 0;
639 foreach (var v1 in verts)
640 {
641 k++;
642 //foreach (var v2 in verts)
643 //{
644 for (int j = k; j < verts.Length; j++)
645 {
646 // {
647 // var v1 = verts[j];
648 var v2 = verts[j];
649
650
651 if (v1 == v2) continue;
652 var dist = Vector3.Distance(v1, v2);
653 if (dist > maxlength) continue;
654 bool ok = false;
655 for (int i = 0; i < tri.Length - 2; i += 3)
656 {
657 List<Vector3> v = new List<Vector3>() { verts[tri[i]], verts[tri[i + 1]], verts[tri[i + 2]] };
658 if (v.Contains(v1) && v.Contains(v2))
659 {
660 ok = true;
661 break;
662 }
663 }
664 if (!ok) continue;
665
666
667 if (!sameLength.ContainsKey(dist))
668 {
669 sameLength.Add(dist, new List<Vector3>() { v1, v2 });
670 }
671 else
672 {
673 sameLength[dist].Add(v1);
674 sameLength[dist].Add(v2);
675 }
676 }
677 yield return null;
678 }
679
680 Debug.Log($"num of diff lenghts b4 merge: {sameLength.Count}");
681
682 var mergedDict = new SortedDictionary<float, List<Vector3>>();
683 var prevKey = 0f;
684 var usingKey = 0f;
685 var mergeMaxDiff = (percent / 100).magnitude;
686
687 foreach (var kv in sameLength)
688 {
689 var kvvCopy = kv.Value;
690 for (int i = 0; i < kv.Value.Count - 1; i += 2)
691 {
692 Vector3 v1 = kv.Value[i];
693 Vector3 v2 = kv.Value[i + 1];
694
695 var count1 = 0;
696 var count2 = 0;
697
698 foreach (var kv2 in sameLength)
699 {
700 count1 += kv2.Value.Count(x => x == v1);
701 count2 += kv2.Value.Count(x => x == v2);
702 }
703 if (count1 == 1 && count2 == 1)
704 {
705 kvvCopy.Remove(v1);
706 kvvCopy.Remove(v2);
707 }
708 }
709 if (kvvCopy.Count <= 1)
710 {
711 continue;
712 }
713 kv.Value.Clear();
714 kv.Value.AddRange(kvvCopy);
715
716 if (prevKey == 0)
717 {
718 prevKey = kv.Key;
719 usingKey = kv.Key;
720 mergedDict.Add(kv.Key, kv.Value);
721 continue;
722 }
723 if (Mathf.Abs(prevKey - kv.Key) < mergeMaxDiff)
724 {
725 mergedDict[usingKey].AddRange(kv.Value);
726 }
727 else
728 {
729 usingKey = kv.Key;
730 mergedDict.Add(kv.Key, kv.Value);
731 }
732 prevKey = kv.Key;
733 }
734 Debug.Log($"num of diff lenghts after merge: {mergedDict.Count}");
735
736 sameLength.Clear();
737 sameLength = mergedDict;
738
739 for (int i = 0; i < sameLength.Count; i++)
740 {
741 colors.Add(new Color(Random.value, Random.value, Random.value));
742 }
743 }
744
745 SortedDictionary<float, List<Vector3>> sameLength = new SortedDictionary<float, List<Vector3>>();
746 List<Color> colors = new List<Color>();
747 private void OnDrawGizmosSelected()
748 {
749 int ci = 0;
750 foreach (var kvp in sameLength)
751 {
752 if (colors.Count == 0)
753 Gizmos.color = Color.grey;
754 else
755 Gizmos.color = colors[ci];
756 ci++;
757 //Gizmos.color = Color.magenta;
758 if (kvp.Value.Count > 2)
759 {
760 for (int i = 0; i < kvp.Value.Count; i += 2)
761 {
762 Gizmos.DrawLine(kvp.Value[i] * transform.localScale.x + transform.position, kvp.Value[i + 1] * transform.localScale.x + transform.position);
763 }
764 }
765 }
766 }
767
768 public Transform targetObject;
769 [Button]
770 void GetUVPos()
771 {
772 var meshFilter = targetObject.GetComponent<MeshFilter>();
773 var skinnedMeshRenderer = targetObject.GetComponent<SkinnedMeshRenderer>();
774 MeshOperator meshOperator = null;
775 Bounds myBounds;
776 if (meshFilter != null)
777 {
778 meshOperator = new MeshOperator(meshFilter.sharedMesh);
779 myBounds = meshFilter.sharedMesh.bounds;
780
781 Vector3[] vertices = meshFilter.mesh.vertices;
782
783 // create new colors array where the colors will be created.
784 UnityEngine.Color[] colors = new UnityEngine.Color[vertices.Length];
785
786 for (int i = 0; i < vertices.Length; i++)
787 colors[i] = UnityEngine.Color.Lerp(UnityEngine.Color.red, UnityEngine.Color.green, vertices[i].y);
788
789 // assign the array of colors to the Mesh.
790 meshFilter.mesh.colors = colors;
791
792
793
794 }
795 else if (skinnedMeshRenderer != null)
796 meshOperator = new MeshOperator(skinnedMeshRenderer.sharedMesh);
797
798
799 Vector2 uv = default;
800
801 var renderCamera = Camera.main;
802
803 Vector3 p = targetObject.InverseTransformPoint(transform.position);
804 Matrix4x4 mvp = renderCamera.projectionMatrix * renderCamera.worldToCameraMatrix * targetObject.localToWorldMatrix;
805
806 meshOperator?.LocalPointToUV(p, mvp, out uv);
807
808 if (uv != default)
809 {
810 Debug.Log(uv.ToString());
811 }
812
813 }
814#endif
815#endif
816
817 [DllImport("user32.dll")]
818
819 private static extern IntPtr FindWindow(string className, string windowName);
820 [DllImport("gdi32.dll")]
821 static extern bool BitBlt(IntPtr hdcDest, int nxDest, int nyDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
822
823 [DllImport("gdi32.dll")]
824 static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int width, int nHeight);
825
826 [DllImport("gdi32.dll")]
827 static extern IntPtr CreateCompatibleDC(IntPtr hdc);
828
829 [DllImport("gdi32.dll")]
830 static extern IntPtr DeleteDC(IntPtr hdc);
831
832 [DllImport("gdi32.dll")]
833 static extern IntPtr DeleteObject(IntPtr hObject);
834
835 [DllImport("user32.dll")]
836 static extern IntPtr GetDesktopWindow();
837
838 [DllImport("user32.dll")]
839 static extern IntPtr GetWindowDC(IntPtr hWnd);
840
841 [DllImport("user32.dll")]
842 static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDc);
843
844 [DllImport("gdi32.dll")]
845 static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
846
847 const int SRCCOPY = 0x00CC0020;
848
849 const int CAPTUREBLT = 0x40000000;
850
851#if !UNITY_WEBGL
852 public static Bitmap CaptureRegion(Rectangle region)
853 {
854 IntPtr desktophWnd;
855 IntPtr desktopDc;
856 IntPtr memoryDc;
857 IntPtr bitmap;
858 IntPtr oldBitmap;
859 bool success;
860 Bitmap result;
861
862 desktophWnd = GetDesktopWindow();
863 desktopDc = GetWindowDC(desktophWnd);
864 memoryDc = CreateCompatibleDC(desktopDc);
865 bitmap = CreateCompatibleBitmap(desktopDc, region.Width, region.Height);
866 oldBitmap = SelectObject(memoryDc, bitmap);
867
868 success = BitBlt(memoryDc, 0, 0, region.Width, region.Height, desktopDc, region.Left, region.Top, SRCCOPY | CAPTUREBLT);
869
870 try
871 {
872 if (!success)
873 {
874 throw new System.ComponentModel.Win32Exception();
875 }
876
877 result = Image.FromHbitmap(bitmap);
878 }
879 finally
880 {
881 SelectObject(memoryDc, oldBitmap);
882 DeleteObject(bitmap);
883 DeleteDC(memoryDc);
884 ReleaseDC(desktophWnd, desktopDc);
885 }
886
887 return result;
888 }
889 [DllImport("user32.dll", SetLastError = true)]
890 public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
891
892 [StructLayout(LayoutKind.Sequential)]
893 public struct RECT
894 {
895 public int left;
896 public int top;
897 public int right;
898 public int bottom;
899 }
900
901 public static Bitmap CaptureWindow(IntPtr hWnd)
902 {
903 RECT region;
904
905 GetWindowRect(hWnd, out region);
906
907 return CaptureRegion(Rectangle.FromLTRB(region.left, region.top, region.right, region.bottom));
908 }
909#endif
910}
UnityEngine.Component Component
UnityEngine.UI.Button Button
Definition: Pointer.cs:7
UnityEngine.Random Random
UnityEngine.Debug Debug
Definition: TanodaServer.cs:19
System.Drawing.Image Image
Definition: TestScript.cs:37
WebSocketSharp.ErrorEventArgs ErrorEventArgs
Definition: TestScript.cs:24
UnityEngine.Color Color
Definition: TestScript.cs:32
void ClearAll()
Definition: Controller.cs:719
IEnumerator LoadControllerFromJSON(Controller controller)
Definition: Controller.cs:91
static Controller Instance
Definition: Controller.cs:16
Texture paint to canvas. To set the per-material.
Definition: InkCanvas.cs:23
A class that manipulates Mesh.
Definition: MeshOperator.cs:12
static FileDragAndDrop instance
static void LoadLevel(string levelJson, bool ssol=false)
Definition: pb_Scene.cs:238
static LevelEditorOnLoaded instance
static LineDrawer Instance
Definition: LineDrawer.cs:16
Definition: Macro.cs:12
static Bounds GetBounds(GameObject go)
Definition: Macro.cs:482
static Vector3 ClampAngle(Vector3 value)
Definition: Macro.cs:303
static void Change(Material mat, string shaderName)
Definition: ShaderChanger.cs:7
static Bitmap CaptureWindow(IntPtr hWnd)
Definition: TestScript.cs:901
Transform fromRot
Definition: TestScript.cs:81
static bool GetWindowRect(IntPtr hwnd, out RECT lpRect)
GameObject to
Definition: TestScript.cs:138
Texture2D toPng
Definition: TestScript.cs:83
GameObject hand
Definition: TestScript.cs:138
GameObject from
Definition: TestScript.cs:138
GameObject moveItem
Definition: TestScript.cs:138
Texture2D DeCompress(Texture2D source)
Definition: TestScript.cs:89
static Bitmap CaptureRegion(Rectangle region)
Definition: TestScript.cs:852
Transform toRot
Definition: TestScript.cs:81
Definition: ClipPainter.cs:5