# AC3D
# Copyright (c) 2004, Inivis Limited. All rights reserved.

set last_save_settings 0

proc prefs_changed { } {
global prefs_recalc_normals
global prefs_save_settings_on_exit
global last_save_settings

	 if { ! $prefs_recalc_normals } {
		 if { ![winfo exists .recalc_normals] } {
			 cbutton .recalc_normals "Recalc normals" "ac3d recalc_normals_all; ac3d redraw_3d"
			 add_balloon .recalc_normals "Force recalculation of lighting normals"
			 pack .recalc_normals -in .cp -side top
		 }
	 } else {
		 catch {destroy .recalc_normals }
	 }

	 set_socket_commands

	if { ($last_save_settings != $prefs_save_settings_on_exit) && (!$prefs_save_settings_on_exit) } {
		set answer [tk_messageBox -message "'Save settings on Exit' is now off - You must save settings now if you want this to be remembered.\n\n(to save settings in the future, you can use the save button which will now be at the bottom of the settings dialog)\n\nSave the current settings now?" -title "Save settings?" -type yesno -icon question]
		case $answer {
			yes {
				 ac3d save_settings
				 }
			no {}
		}
	}

	ac3d redraw_all

}


proc show_settings {} {

global prefs_save_settings_on_exit
global last_save_settings tcl_platform ac_platform


	set last_save_settings $prefs_save_settings_on_exit

	new_toplevel .panel "Settings"


	set n .panel.notebook
	Notebook:create $n -pages {General "3D View" Appearance Files Advanced} -pad 20 ]
	pack .panel.notebook -fill both -expand 1
	set wg [Notebook:frame $n General]
	set w3 [Notebook:frame $n "3D View"]
	set wap [Notebook:frame $n Appearance]
	
	## printing only under windows
#	if { $tcl_platform(platform) == "windows" } {
#		set wp [Notebook:frame $n Printing]
#	}
	set wad [Notebook:frame $n Advanced]
	
	set	wf [Notebook:frame $n Files]

#return;

set w $wg
 #	 frame .panel.f -relief raised -bd 1


	# GENERAL
	label_edit $wg prefs_drawgrid "Draw grid major" "dimension for the thicker visible lines in the orthographic windows"
	label_edit $wg prefs_grid "Draw Grid minor (snap grid)" "dimension for the thin grid lines - also defines the snap grid\nactive when 'gridsnap' is on"
	label_bool $wg prefs_balloon_help "Balloon help" "Switch these balloons off!"
	label_bool $wg prefs_fit_view_after_load "Fit view after load" "zoom views in towards objects after loading?"
	label_edit $wg prefs_snap_near_pixels "Near snap pixels" "how near the pointer must be to a point before it will snap to it\n(when drawing polys/polylines/lines)"
	label_bool $wg prefs_rotate_about_object_centre "Rotate about object centre?" "when using the mouse to rotate a (single) object - \nuse the mouse point or the object's centre to rotate about?"
	label_bool $wg prefs_show_startup_tips "Show tips on startup" "show the AC3D tip window when the program starts?"
	label_bool $wg prefs_shift_duplicated "Offset dupicates" "if set, duplicate offset the position of the new object/surfaces"
	label_edit $wg prefs_hole_percent "Make hole %" "percentage of hole to make in Surface->make hole"
#	label_edit $wg prefs_bevel_size "Bevel size (units)" "bevel size used in Surface->Bevel" 
	label_edit $wg prefs_mouse_rotate_degs "Mouse rotate (degrees)" "steps of rotations when rotating selections with the mouse" 
	label_edit $wg prefs_move_normal_distance "Move along normal dist." "Distance to move selected surfaces when +/- keys are pressed" 


	# 3D View
	label_col $w3 prefs_col_3dbackground "3D background" "specifies the background col of the 3d windows"
	label_col $w3 prefs_col_3dgrid "3D grid" "specifies the col of the 3D grid"
	label_edit $w3 prefs_grid3d_square "3D Grid dimension" "size (units) of grid in 3D windows"
	label_edit $w3 prefs_grid3d_size "3D Grid square" "size (units) of one grid square 3D windows"
	# 3d grid lw doesn't work
	label_edit $w3 prefs_grid_3d_line_width "3D Grid line thickness" "width of lines that make up the 3D window's grid"
	label_edit $w3 prefs_3d_axis_line_width "3D axis line thickness" "width of lines that make up the 3D window's axis"

	label_edit $w3 prefs_axis_size "3D Axis size" "size (m) of axis in 3D windows"
	label_edit $w3 prefs_walk_move_speed "Walkmode mouse move speed" "distance to move each step when mouse is used in the 3D window's walk-mode"
	label_edit $w3 prefs_walk_turn_speed "Walkmode mouse turn speed" "degree at which to turn when mouse is moved left/right when flying in 3D window"
	label_edit $w3 prefs_fov "Default FOV" "field of view of the 3D camera (1-180 degs)"


	# APPEARANCE
	label_edit $wap prefs_vert_size "Vertex point size (pixels)" "adjust vertex squares in orth windows"
	label_edit $wap prefs_handle_size "Handle size (pixels)" "size of handles at edges of the selection box"
	label_edit $wap prefs_size_show_normals "Size of display normals" "the size to draw the lines representing surface normals"
	label_bool $wap prefs_show_window_labels "Display window labels?" "Show the window labels at the top of the orth windows?"
	label_bool $wap prefs_polygon_offset "Polygon Offset" "If set, polygons are moved back slightly so that surface outlines can be seen more clearly"


	label_col $wap prefs_col_background "Orth background col" "specifies the background col of the orth windows"
	label_col $wap prefs_col_grid "Orth grid col" "specifies the col of the orth grids"
	label_col $wap prefs_col_vert "Vertex col" "Unselected vertex col"
	label_col $wap prefs_col_selvert "Vertex (selected) col" "Selected vertex col"


#doesn;t work:
	label_col $wap prefs_uveditor_bgcol "TCE background col" "background col of Texture Coordinate Editor"
	label_col $wap prefs_uveditor_edgecol "TCE edge col" "col of lines drawn in the Texture Coordinate Editor"

	label_edit $wap prefs_bb_line_width "BB line thickness" "width of the bounded box that is drawn arounf the current selection"
	label_edit $wap prefs_surface_line_width "Surface outline thickness" "line width of surface outline"
	label_edit $wap prefs_surface_selected_line_width "Surface outline thickness (sel)" "line width of a selected surface outline"

	label_bool $wap prefs_selected_surface_stipple "Stipple selected surfaces" "stipple a pattern over surfaces that are selected,\n ratherthan just outlining them"


	# FILE
#	label_edit $wf prefs_fontpath "Fontpath" "File path for AC3D font file used in 'Add text'"

	label_edit $wf prefs_pov_file_header "POV header" "Text output at the very top of a POV file"
	label_bool $wf prefs_pov_use_object_data "Use object data for POV files" "Use object data in POV file output"

	label_bool $wf prefs_swap_3ds_yz "3DS swap yz" "if set, 3DS importer and exporter will swap y and z values"
	label_bool $wf prefs_optimize_3ds_import "3DS optimize vertices" "remove duplicate vertices when importing 3DS files"

	label_bool $wf prefs_output_vrml_normals "Output VRML normals" \
		 "some VRML browsers calculate normals, so don't need them supplied.\nswitching this off saves on file size"
	label_bool $wf prefs_output_vrml_textures "Output VRML textures" \
		 "controls if textures and texture coordinates are generated in VRML files"

	label_bool $wf prefs_vrml2_use_object_name_as_desc "VRML2 object names as desc" \
		 "specifies if the object names are used as anchor descriptions \n(objects must have a URL for an anchor to be created)"

	label_bool $wf prefs_output_rib_header "Output Renderman(.rib) header" "output world info/lights etc at start of rib file?"

	label_bool $wf prefs_rib_use_object_data "Use object data for RIB files" "Use object data in RIB (Renderman) file output"
	label_bool $wf prefs_output_rib_textures "Output RIB (Renderman) textures" "Output textures/UV coordinates in Renderman RIB files (untested)" 

	label_bool $wf prefs_md2_swap_yz "MD2 swap yz" "if set, MD2 importer and exporter will swap y and z values"


#	if { $tcl_platform(platform) == "windows" } {
#		# PRINTING
#		label_bool $wp prefs_printing_force_white_background "Force white background" "ignore the current 3D window bacground and put a white background on the image?" 
#		label_bool $wp prefs_printing_centre "Center the image" "Centre the image on the page?" 
#		label_bool $wp prefs_printing_scale_to_fit "Scale to fit" "Scale the image to fit the page?" 
#	}

	# ADVANCED
	label_edit $wad prefs_tcl_socket_port "TCL socket port" "Port number for socket AC3D's TCL socket"
	label_bool $wad prefs_allow_socket_commands "Allow socket commands" "If on, external programs can connect to AC3D and send commands to it"
#	label_bool $wad prefs_use_textures_for_background_images "Use texturing for bg images" "draw background images with texturemapping or DrawPixel"
	label_bool $wad prefs_doublebuffer_orth "Doublebuffer orth windows" "setting this will make updating less flickery"
	label_bool $wad prefs_save_settings_on_exit "Save settings on exit" "Automatically save the settings file when you quit?"
#	label_bool $wad prefs_memory_checks "Memory Checks" "FOR DEBUGGING PURPOSES. Tracks memory and warns on freeing same address twice"
#	label_bool $wad prefs_share_opengl_contexts "Share Opengl Contexts" "Some older graphics cards have problems sharing,\nswitch this off if you have the latest drivers and are still getting blank views.\nSide effect is that you may not get textures appearing in all windows.\nNOTE THAT AC3D MUST BE RESTARTED FOR THIS SETTING TO TAKE EFFECT"
	label_bool $wad prefs_wireframe_select_lines "Select wireframe" "in wireframe mode, select by lines rather than polygons?"
	label_bool $wad prefs_nav_select "Nav select" "if set, dragging outside the selection in 3d views will navigate (e.g. spin), rather than drag-selecting"


	label_bool $wad prefs_triangulate_quads "Triangulate quads" "If on, rendering will ensure that concave four sided polygons are drawn correctly.\nThis will be slower but gives a correct shape."

	if { $tcl_platform(platform) == "windows" } {
		label_bool $wad prefs_windows_show_console  "Show Windows console" "Keep the startup console visible? (useful for debugging purposes)"
	}

	label_edit $wad prefs_pick_pixel_range "Pick range (pixels)" "range used for click selections\n(this should be the same as the\nvertex size if you want to select vertices by clicking)"
	label_edit $wad prefs_default_crease_angle "Default crease angle (degs 0.0-180.0)" "form a shading crease when angles between smooth surfaces are greater than this angle\nSetting surface to Flat forces flat shading."

	label_edit $wad prefs_subdivision_max_polys "Subdivision max surfaces" "Defines the maximum number of surfaces for a subdivision.\nThis limit is defined because subdivision quadruples the number of surfaces at each level.\nThis increases memory requirements and reduces overall speed."


	# non-windows, allow slection of a web browser
	if { $ac_platform == "Linux" } {
		label_filename $wad prefs_web_browser "Web browser" "Default web browser to use when viewing web pages from AC3D"
	}

	label_edit $wad prefs_material_default_ambient "Default material ambient" "\[0.0->1.0\] default RGB component values for a new material"
	label_edit $wad prefs_material_default_emissive "Default material emissive" "\[0.0->1.0\] default RGB component values for a new material"
	label_edit $wad prefs_material_default_specular "Default material specular" "\[0.0->1.0\] default RGB component values for a new material"
	label_edit $wad prefs_material_default_shininess "Default material shininess" "\[0->128\] default shininess for a new material"


	frame .panel.buttons
	
	button .panel.buttons.ok -text "Close" -command {
		destroy .panel
		prefs_changed
	}
	button .panel.buttons.save -text "Save" -command {
#		 destroy .panel
		ac3d save_settings
		prefs_changed
	}
	button .panel.buttons.reset -text "Reset to defaults" -command {
		destroy .panel
		ac3d prefs_set_defaults
		reset_recent_files_menu
		show_settings
	}
	pack .panel.buttons.ok -side left
	pack .panel.buttons.reset -side right

	if { !$prefs_save_settings_on_exit } {
		pack .panel.buttons.save -side right
	}

#	 pack .panel.f -side top
	pack .panel.buttons -side bottom

centre_window_on_screen .panel

	grab set .panel
	tkwait window .panel

}



proc label_edit { parent var { text "" } { balloon "" } { width ""} } {

	set row [lindex [grid size $parent] 1]
	set row [expr $row + 1]

	label $parent.lel$row -text $text
	if { $balloon != "" } {
		add_balloon $parent.lel$row $balloon
		}

	entry $parent.le$row -relief sunken -bd 2 -textvariable $var

	if {$width != ""} {
		$parent.le$row configure -width $width
	}
	grid  $parent.lel$row -column 0 -row $row -sticky e
	grid  $parent.le$row -column 1 -row $row -stick w
}




proc label_filename_select { var } {
	upvar #0 $var svar

	if { [file exists $var] } {
		set test [tk_getOpenFile -title "Select file" -initialfile $var];
	} else {
		set test [tk_getOpenFile -title "Select file"];
	}

	if { $test != "" } {set svar $test}

}

proc label_filename { parent var { text "" } { balloon "" } { width ""} } {

	set row [lindex [grid size $parent] 1]
	set row [expr $row + 1]

	label $parent.lel$row -text $text
	if { $balloon != "" } {
		add_balloon $parent.lel$row $balloon
		}

	entry $parent.le$row -relief sunken -bd 2 -textvariable $var

	button $parent.leb$row -text "Browse..." -command "label_filename_select $var"
			

	if {$width != ""} {
		$parent.le$row configure -width $width
	}

	grid  $parent.lel$row -column 0 -row $row -sticky e
	grid  $parent.le$row -column 1 -row $row -stick w
	grid  $parent.leb$row -column 2 -row $row -stick w
}



proc label_bool { parent var { text "" } { balloon "" } } {

	set row [lindex [grid size $parent] 1]
	set row [expr $row + 1]
	label $parent.label_edit_checklab$row -text $text

	ac_checkbutton $parent.label_edit_check$row "" "" $var ""
#	checkbutton $parent.label_edit_check$row -variable $var -highlightthickness 0

	if { $balloon != "" } {
		add_balloon $parent.label_edit_checklab$row $balloon
		}


	grid $parent.label_edit_checklab$row -column 0 -row $row -sticky e
	grid $parent.label_edit_check$row -column 1 -row $row  -sticky w

}






# rgb2dec --
#
#	Turns #rgb into 3 elem list of decimal vals.
#
# Arguments:
#	c		The #rgb hex of the color to translate
# Results:
#	Returns a #RRGGBB or #RRRRGGGGBBBB color
#
proc rgb2dec c {
	set c [string tolower $c]
	if {[regexp -nocase {^#([0-9a-f])([0-9a-f])([0-9a-f])$} $c x r g b]} {
	# double'ing the value make #9fc == #99ffcc
	scan "$r$r $g$g $b$b" "%x %x %x" r g b
	} else {
	if {![regexp {^#([0-9a-f]+)$} $c junk hex] || \
		[set len [string length $hex]]>12 || $len%3 != 0} {
		if {[catch {winfo rgb . $c} rgb]} {
		return -code error "bad color value \"$c\""
		} else {
		return $rgb
		}
	}
	set len [expr {$len/3}]
		scan $hex "%x" rgb
	}
	return $rgb
}

# dec2rgb --
# takes decimal
# Results:
#	Returns a #RRGGBB
#
proc dec2rgb { col } {
 
  set s [format "#%06x" $col] 
  return "$s"
}





proc coledit { but var } {
global prefs_col_3dbackground

	upvar #0 $var col

	set newc  [tk_chooseColor -parent $but -initialcolor [ dec2rgb $col ] ]
	if { $newc != "" } {
		$but configure -bg $newc

		set v [rgb2dec $newc]
		set col $v
		}

}

proc coledit_button { path varname text {command "" } } {

	upvar #0 $varname col

	set b [cbutton $path  $text "coledit $path $varname; $command" "set this col"]
	$b configure -bg [ dec2rgb $col ] 

	return $b
}


proc label_col { parent var { text "" } { balloon "" } } {
global num_label_edit

	set row [lindex [grid size $parent] 1]
	set row [expr $row + 1]


	label $parent.lel$row -text $text
	if { $balloon != "" } {
		add_balloon $parent.lel$row $balloon
		}

	upvar #0 $var col

	set b [ coledit_button $parent.col$row $var "..." ]

	grid  $parent.lel$row -column 0 -row $row -sticky e
	grid  $b -column 1 -row $row  -sticky we
}



