----------------------------------------------------------------------
--  Pivot Align  -  v1.4
--  Align the pivot of selected objects to Min / Mid / Max on each axis
--  of the bounding box. Modes: World, Local (follows rotation), and
--  Working (moves the scene Working Pivot). "Use selection bbox" aligns
--  by the combined bounding box of several selected objects. Live viewport
--  preview, a view-following cube widget, and Reset to restore.
--
--  Author : Marcelo Souza   ( kumodot // @msouza3d )
--  Site   : https://www.kumodot.com
--  (c) 2026 Kumodot - free to use, please keep this credit.
----------------------------------------------------------------------
global pt_ix = 1        -- 0=Min 1=Mid 2=Max
global pt_iy = 1
global pt_iz = 1
global pt_space = #world   -- #world | #local | #working
global pt_live = true
global pt_sel = false      -- use the whole-selection bbox (objects or sub-objects)
global pt_dots = #()       -- last drawn dots: #([sx,sy], ix, iy, iz, depth)
global pt_lastView = ""    -- viewport TM signature for live refresh
global pt_orig = #()       -- captured originals: #( #(node, pivotPoint) ... )
global pt_origWP = undefined  -- original Working Pivot TM, for Reset

global pt_edges = #(
	#(-1,-1,-1, 1,-1,-1), #(1,-1,-1, 1,1,-1), #(1,1,-1, -1,1,-1), #(-1,1,-1, -1,-1,-1),
	#(-1,-1, 1, 1,-1, 1), #(1,-1, 1, 1,1, 1), #(1,1, 1, -1,1, 1), #(-1,1, 1, -1,-1, 1),
	#(-1,-1,-1, -1,-1,1), #(1,-1,-1, 1,-1,1), #(1,1,-1, 1,1,1), #(-1,1,-1, -1,1,1)
)

fn pt_col a r g b = (dotNetClass "System.Drawing.Color").FromArgb a r g b
fn pt_depthCompare a b = a[5] - b[5]

fn pt_proj x y z M o rot sc cx cy =
(
	local wd = [x,y,z] * rot
	local vd = ([wd.x, wd.y, wd.z] * M) - o
	[cx + vd.x * sc, cy - vd.y * sc, vd.z]
)

fn pt_alignPivotOne obj ix iy iz space =
(
	if space == #local then
	(
		local tm = obj.objecttransform
		local bb = nodeGetBoundingBox obj tm
		local f = #(0.0,0.5,1.0)
		local lp = [ bb[1].x + (bb[2].x-bb[1].x)*f[ix+1],
					 bb[1].y + (bb[2].y-bb[1].y)*f[iy+1],
					 bb[1].z + (bb[2].z-bb[1].z)*f[iz+1] ]
		obj.pivot = lp * tm
	)
	else
	(
		local lo = obj.min; local ce = obj.center; local hi = obj.max
		obj.pivot = [ (#(lo.x,ce.x,hi.x))[ix+1], (#(lo.y,ce.y,hi.y))[iy+1], (#(lo.z,ce.z,hi.z))[iz+1] ]
	)
)

-- remember each node's pivot the first time we touch it this session
fn pt_capture =
(
	for obj in selection where (isValidNode obj) do
	(
		local found = false
		for rec in pt_orig do if rec[1] == obj do found = true
		if not found do append pt_orig #(obj, obj.pivot)
	)
)

fn pt_reset =
(
	local did = false
	if pt_orig.count > 0 do
	(
		undo "Reset Pivot" on ( for rec in pt_orig do ( if isValidNode rec[1] do rec[1].pivot = rec[2] ) )
		pt_orig = #(); did = true
	)
	if pt_origWP != undefined do ( try (workingpivot.setTM pt_origWP) catch (); pt_origWP = undefined; did = true )
	did
)

-- combined WORLD bounding box of the selected objects -> #(min, max, center)
fn pt_selBBox =
(
	local lo = [1e9,1e9,1e9]; local hi = [-1e9,-1e9,-1e9]
	for obj in selection do
	(
		local omin = obj.min; local omax = obj.max
		lo = [ amin lo.x omin.x, amin lo.y omin.y, amin lo.z omin.z ]
		hi = [ amax hi.x omax.x, amax hi.y omax.y, amax hi.z omax.z ]
	)
	#( lo, hi, (lo + hi) / 2.0 )
)

-- move the scene Working Pivot to a world point (keeps its orientation)
fn pt_workingTo point =
(
	try
	(
		local editing = false
		try (editing = workingpivot.IsEditing()) catch ()
		local wtm = workingpivot.getTM()
		wtm.row4 = point
		workingpivot.setTM wtm
		-- if in Edit Working Pivot mode, re-enter it so the gizmo re-reads the TM
		if editing do ( try ( workingpivot.EndEditing(); workingpivot.StartEditing() ) catch () )
		redrawViews()
	)
	catch ( messageBox "Working Pivot isn't available via script in this Max version." title:"Pivot Align" )
)

fn pt_bboxPoint bb ix iy iz =
(
	[ (#(bb[1].x, bb[3].x, bb[2].x))[ix+1],
	  (#(bb[1].y, bb[3].y, bb[2].y))[iy+1],
	  (#(bb[1].z, bb[3].z, bb[2].z))[iz+1] ]
)

fn pt_apply =
(
	if selection.count == 0 do return false
	if pt_space == #working then
	(
		if pt_origWP == undefined do ( try (pt_origWP = workingpivot.getTM()) catch () )
		pt_workingTo (pt_bboxPoint (pt_selBBox()) pt_ix pt_iy pt_iz)
	)
	else
	(
		pt_capture()
		if pt_sel then
		(
			local pnt = pt_bboxPoint (pt_selBBox()) pt_ix pt_iy pt_iz
			undo "Align Pivot" on ( for obj in selection do ( if isValidNode obj do obj.pivot = pnt ) )
		)
		else
			undo "Align Pivot" on ( for obj in selection do ( try (pt_alignPivotOne obj pt_ix pt_iy pt_iz pt_space) catch () ) )
	)
	true
)

rollout pt_roll "Pivot Align  v1.4"
(
	dotNetControl pb "System.Windows.Forms.PictureBox" pos:[10,8] width:180 height:180
	label lblSel "" pos:[10,194] width:182 align:#left
	radiobuttons rbSpace "Mode" labels:#("World","Local","Working") columns:3 pos:[12,212]
	radiobuttons rbX "X axis" labels:#("Min","Mid","Max") columns:3 pos:[12,238]
	radiobuttons rbY "Y axis" labels:#("Min","Mid","Max") columns:3 pos:[12,274]
	radiobuttons rbZ "Z axis" labels:#("Min","Mid","Max") columns:3 pos:[12,310]
	checkbox chkSel "Use selection bbox" checked:false pos:[12,348] width:184
	checkbox chkLive "Live" checked:true pos:[12,372]
	button btApply "Apply" width:58 height:24 pos:[60,368]
	button btReset "Reset" width:68 height:24 pos:[122,368]
	button btC "Center" width:56 across:3 pos:[12,400]
	button btB "Base" width:56 pos:[70,400]
	button btT "Top" width:56 pos:[128,400]
	dotNetControl lblCred "System.Windows.Forms.Label" pos:[2,432] width:200 height:16
	timer clock interval:250 active:true

	fn syncLabel =
	(
		local n = #("Min","Mid","Max")
		local spn = (if pt_space==#world then "World" else if pt_space==#local then "Local" else "Working")
		local tag = spn + (if pt_sel then " +Sel" else "")
		lblSel.text = "X:" + n[pt_ix+1] + "  Y:" + n[pt_iy+1] + "  Z:" + n[pt_iz+1] + "   [" + tag + "]"
	)

	fn redraw =
	(
		try
		(
			local bmp = dotNetObject "System.Drawing.Bitmap" 180 180
			local g = (dotNetClass "System.Drawing.Graphics").FromImage bmp
			g.SmoothingMode = (dotNetClass "System.Drawing.Drawing2D.SmoothingMode").AntiAlias
			g.Clear (pt_col 255 60 60 63)

			local M = viewport.getTM()
			local o = [0,0,0] * M
			local rot = matrix3 1
			if pt_space == #local and not pt_sel and selection.count > 0 do ( try (rot = (selection[1].objecttransform.rotationpart) as matrix3) catch () )
			local sc = 42.0; local cx = 90.0; local cy = 92.0

			pt_dots = #()
			for iz = 0 to 2 do for iy = 0 to 2 do for ix = 0 to 2 do
			(
				local p = pt_proj (ix-1) (iy-1) (iz-1) M o rot sc cx cy
				append pt_dots #([p[1],p[2]], ix, iy, iz, p[3])
			)
			qsort pt_dots pt_depthCompare

			local penGrid = dotNetObject "System.Drawing.Pen" (pt_col 45 120 120 128) 1.0
			for u = -1 to 1 do for v = -1 to 1 do
			(
				local la = pt_proj -1 u v M o rot sc cx cy; local lb = pt_proj 1 u v M o rot sc cx cy; g.DrawLine penGrid la[1] la[2] lb[1] lb[2]
				local lc = pt_proj u -1 v M o rot sc cx cy; local ld = pt_proj u 1 v M o rot sc cx cy; g.DrawLine penGrid lc[1] lc[2] ld[1] ld[2]
				local le = pt_proj u v -1 M o rot sc cx cy; local lf = pt_proj u v 1 M o rot sc cx cy; g.DrawLine penGrid le[1] le[2] lf[1] lf[2]
			)

			local penE = dotNetObject "System.Drawing.Pen" (pt_col 255 130 130 138) 1.0
			for e in pt_edges do
			(
				local a = pt_proj e[1] e[2] e[3] M o rot sc cx cy
				local b = pt_proj e[4] e[5] e[6] M o rot sc cx cy
				g.DrawLine penE a[1] a[2] b[1] b[2]
			)

			local oc = pt_proj -1 -1 -1 M o rot sc cx cy
			local ex = pt_proj 1 -1 -1 M o rot sc cx cy
			local ey = pt_proj -1 1 -1 M o rot sc cx cy
			local ez = pt_proj -1 -1 1 M o rot sc cx cy
			g.DrawLine (dotNetObject "System.Drawing.Pen" (pt_col 255 232 86 86) 2.0) oc[1] oc[2] ex[1] ex[2]
			g.DrawLine (dotNetObject "System.Drawing.Pen" (pt_col 255 120 205 110) 2.0) oc[1] oc[2] ey[1] ey[2]
			g.DrawLine (dotNetObject "System.Drawing.Pen" (pt_col 255 96 160 240) 2.0) oc[1] oc[2] ez[1] ez[2]

			local brDot = dotNetObject "System.Drawing.SolidBrush" (pt_col 255 175 175 182)
			local brSel = dotNetObject "System.Drawing.SolidBrush" (pt_col 255 255 178 40)
			local penSel = dotNetObject "System.Drawing.Pen" (pt_col 255 255 255 255) 1.5
			for d in pt_dots do
			(
				local isSel = (d[2]==pt_ix and d[3]==pt_iy and d[4]==pt_iz)
				if isSel then ( g.FillEllipse brSel (d[1][1]-6) (d[1][2]-6) 12 12; g.DrawEllipse penSel (d[1][1]-6) (d[1][2]-6) 12 12 )
				else g.FillEllipse brDot (d[1][1]-3) (d[1][2]-3) 6 6
			)
			g.Dispose()
			pb.Image = bmp
		) catch ()
		syncLabel()
	)

	fn pushState =
	(
		rbX.state = pt_ix+1; rbY.state = pt_iy+1; rbZ.state = pt_iz+1
		redraw()
		if pt_live do pt_apply()
	)

	on pb mouseDown s a do
	(
		local best = 0; local bd = -1e9
		for i = 1 to pt_dots.count do
		(
			local d = pt_dots[i]
			local dx = d[1][1]-a.X; local dy = d[1][2]-a.Y
			if (dx*dx + dy*dy) <= 120 and d[5] >= bd do ( bd = d[5]; best = i )
		)
		if best > 0 do ( local d = pt_dots[best]; pt_ix=d[2]; pt_iy=d[3]; pt_iz=d[4]; pushState() )
	)

	on clock tick do
	(
		try ( local s = (viewport.getTM()) as string; if s != pt_lastView do ( pt_lastView = s; redraw() ) ) catch ()
	)

	on rbX changed st do ( pt_ix = st-1; redraw(); if pt_live do pt_apply() )
	on rbY changed st do ( pt_iy = st-1; redraw(); if pt_live do pt_apply() )
	on rbZ changed st do ( pt_iz = st-1; redraw(); if pt_live do pt_apply() )
	on rbSpace changed st do ( pt_space = (if st==1 then #world else if st==2 then #local else #working); redraw(); if pt_live do pt_apply() )
	on chkSel changed st do ( pt_sel = st; redraw(); if pt_live do pt_apply() )
	on chkLive changed st do pt_live = st
	on btApply pressed do pt_apply()
	on btReset pressed do pt_reset()
	on btC pressed do ( pt_ix=1; pt_iy=1; pt_iz=1; pushState() )
	on btB pressed do ( pt_ix=1; pt_iy=1; pt_iz=0; pushState() )
	on btT pressed do ( pt_ix=1; pt_iy=1; pt_iz=2; pushState() )

	on pt_roll open do
	(
		try
		(
			lblCred.Text = "kumodot // @msouza3d 2026"
			lblCred.TextAlign = (dotNetClass "System.Drawing.ContentAlignment").MiddleCenter
			lblCred.ForeColor = (pt_col 255 150 150 156)
			lblCred.Font = dotNetObject "System.Drawing.Font" "Segoe UI" 7.5
		) catch ()
		rbSpace.state = (if pt_space==#world then 1 else if pt_space==#local then 2 else 3)
		rbX.state = pt_ix+1; rbY.state = pt_iy+1; rbZ.state = pt_iz+1
		chkSel.checked = pt_sel
		chkLive.checked = pt_live
		redraw()
	)
)

try (destroyDialog pt_roll) catch ()
createDialog pt_roll 204 456
