EditorGUI Modifying Displayed Textures (Painting)

I know it sound insane to create a “paint program” but its more of a 2D scene editor that I’m hoping to create but I need to be able to figure out some basic drawing primitives. My code is as follows. If you run the code, you’ll notice that the canvas updates every so often without consideration as to when and the coordinates are off. I can’t determine the position of the canvas.

Any idea of how I might solve these two problems?

Cheers,
Jeremy

using UnityEditor;
using UnityEngine;
using System.Collections;

public class TestEditor : EditorWindow {
	
	
	[MenuItem("Editor/TestEditor")]
	static void ShowWindow ()
	{
		EditorWindow.GetWindow<TestEditor> ();
	}
	
	Texture2D canvas;
	bool isInitialized = false;
	
	public TestEditor()	
	{
		
	}
	
	public void OnGUI()
	{
		this.wantsMouseMove = true;
		
		if (!isInitialized)
		{
			canvas = new Texture2D(200,200, TextureFormat.ARGB32, false);
			canvas.wrapMode = TextureWrapMode.Clamp;
			for(int x = 0; x < canvas.width; x++)
				for(int y = 0; y < canvas.height; y++)
					canvas.SetPixel(x,y,Color.white);
			canvas.Apply();
			isInitialized = true;	
		}
		GUILayout.Box (canvas);
		
		Event current = Event.current;
		
		switch(current.type)
		{
		case EventType.MouseMove:
			int x = (int) current.mousePosition.x;
			int y = (int) current.mousePosition.y;
			Debug.Log("MouseMove:" + x + ":" + y);
			
			if (x < canvas.width  y < canvas.height) 
			{
				canvas.SetPixel(x,y,Color.black);
				canvas.Apply();
			}

			break;
		case EventType.MouseDown:
			Debug.Log("MouseDown:" + current.mousePosition.x + ":" + current.mousePosition.y);
			break;
		case EventType.MouseUp:
			Debug.Log("MouseUp:" + current.mousePosition.x + ":" + current.mousePosition.y);
			break;
		}
	}
		
}

The coordinates are off because the Y axis of the mouse position increases down the screen (ie, zero at top) while the pixel coordinates for the texture have the Y axis increasing upwards. (This is to match the arrangement of the UV coordinates, in case you’re wondering why the two are different.) You need to subtract the mouse position’s Y coordinate from the texture’s height to get the flipped Y coordinate relative to the texture.

As for the other matter, it is not to do with the frequency of mouse move events as you can demonstrate yourself by logging the time on each event. I suspect that the texture itself only gets updated occasionally in the editor, but I’ll get this confirmed by someone who knows a lot more about it than I do. Stay tuned…

Ya, I discovered the mouse inversion afterward. That was easily fixed. Ether the delay is in the Apply of the Texture or in the infrequency of the OnGui. It doesn’t seem fixable in the Editor GUI which limits the extensibility of the Editor.

Jeremy

The piece I’m missing is

HandleUtility.Repaint()

This triggers an immediate update.