func (v *SearchEntry) native() *C.GtkSearchEntry {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkSearchEntry(p)
}

func ( v * SearchEntry ) native ( ) * C . GtkSearchEntry { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkSearchEntry ( p ) }

// native returns a pointer to the underlying GtkSearchEntry.

native returns a pointer to the underlying GtkSearchEntry .


func (v *SelectionData) native() *C.GtkSelectionData {
	if v == nil {
		return nil
	}
	return v.GtkSelectionData
}

func ( v * SelectionData ) native ( ) * C . GtkSelectionData { if v == nil { return nil } return v . GtkSelectionData }

// native returns a pointer to the underlying GtkSelectionData.

native returns a pointer to the underlying GtkSelectionData .


func (v *SelectionData) GetData() (data []byte) {
	var length C.gint
	c := C.gtk_selection_data_get_data_with_length(v.native(), &length)
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data))
	sliceHeader.Data = uintptr(unsafe.Pointer(c))
	sliceHeader.Len = int(length)
	sliceHeader.Cap = int(length)
	return
}

func ( v * SelectionData ) GetData ( ) ( data [ ] byte ) { var length C . gint c := C . gtk_selection_data_get_data_with_length ( v . native ( ) , & length ) sliceHeader := ( * reflect . SliceHeader ) ( unsafe . Pointer ( & data ) ) sliceHeader . Data = uintptr ( unsafe . Pointer ( c ) ) sliceHeader . Len = int ( length ) sliceHeader . Cap = int ( length ) return }

// GetData is a wrapper around gtk_selection_data_get_data_with_length.
// It returns a slice of the correct size with the selection's data.

GetData is a wrapper around gtk_selection_data_get_data_with_length . It returns a slice of the correct size with the selection s data .


func GetData(pointer uintptr) (data []byte) {
	c := (*C.GValue)(unsafe.Pointer(pointer))
	p := (*C.GtkSelectionData)(unsafe.Pointer(c))
	C.gtk_selection_data_get_text(p)

	var byteData []byte
	var length C.gint
	cptr := C.gtk_selection_data_get_data_with_length(p, &length)
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&byteData))
	sliceHeader.Data = uintptr(unsafe.Pointer(cptr))
	sliceHeader.Len = int(length)
	sliceHeader.Cap = int(length)

	return byteData
}

func GetData ( pointer uintptr ) ( data [ ] byte ) { c := ( * C . GValue ) ( unsafe . Pointer ( pointer ) ) p := ( * C . GtkSelectionData ) ( unsafe . Pointer ( c ) ) C . gtk_selection_data_get_text ( p ) var byteData [ ] byte var length C . gint cptr := C . gtk_selection_data_get_data_with_length ( p , & length ) sliceHeader := ( * reflect . SliceHeader ) ( unsafe . Pointer ( & byteData ) ) sliceHeader . Data = uintptr ( unsafe . Pointer ( cptr ) ) sliceHeader . Len = int ( length ) sliceHeader . Cap = int ( length ) return byteData }


func SetData(pointer uintptr, atom gdk.Atom, data []byte) {
	c := (*C.GValue)(unsafe.Pointer(pointer))
	p := (*C.GtkSelectionData)(unsafe.Pointer(c))
	C.gtk_selection_data_set(p, C.GdkAtom(unsafe.Pointer(atom)), C.gint(8), (*C.guchar)(unsafe.Pointer(&data[0])), C.gint(len(data)))
}

func SetData ( pointer uintptr , atom gdk . Atom , data [ ] byte ) { c := ( * C . GValue ) ( unsafe . Pointer ( pointer ) ) p := ( * C . GtkSelectionData ) ( unsafe . Pointer ( c ) ) C . gtk_selection_data_set ( p , C . GdkAtom ( unsafe . Pointer ( atom ) ) , C . gint ( 8 ) , ( * C . guchar ) ( unsafe . Pointer ( & data [ 0 ] ) ) , C . gint ( len ( data ) ) ) }


func DragSetIconPixbuf(context *gdk.DragContext, pixbuf *gdk.Pixbuf, hot_x int, hot_y int) {
	ctx := unsafe.Pointer(context.Native())
	pix := unsafe.Pointer(pixbuf.Native())
	C.gtk_drag_set_icon_pixbuf((*C.GdkDragContext)(ctx), (*C.GdkPixbuf)(pix), C.gint(hot_x), C.gint(hot_y))
}

func DragSetIconPixbuf ( context * gdk . DragContext , pixbuf * gdk . Pixbuf , hot_x int , hot_y int ) { ctx := unsafe . Pointer ( context . Native ( ) ) pix := unsafe . Pointer ( pixbuf . Native ( ) ) C . gtk_drag_set_icon_pixbuf ( ( * C . GdkDragContext ) ( ctx ) , ( * C . GdkPixbuf ) ( pix ) , C . gint ( hot_x ) , C . gint ( hot_y ) ) }


func (v *Separator) native() *C.GtkSeparator {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkSeparator(p)
}

func ( v * Separator ) native ( ) * C . GtkSeparator { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkSeparator ( p ) }

// native returns a pointer to the underlying GtkSeperator.

native returns a pointer to the underlying GtkSeperator .


func (v *SeparatorMenuItem) native() *C.GtkSeparatorMenuItem {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkSeparatorMenuItem(p)
}

func ( v * SeparatorMenuItem ) native ( ) * C . GtkSeparatorMenuItem { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkSeparatorMenuItem ( p ) }

// native returns a pointer to the underlying GtkSeparatorMenuItem.

native returns a pointer to the underlying GtkSeparatorMenuItem .


func (v *SeparatorToolItem) native() *C.GtkSeparatorToolItem {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkSeparatorToolItem(p)
}

func ( v * SeparatorToolItem ) native ( ) * C . GtkSeparatorToolItem { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkSeparatorToolItem ( p ) }

// native returns a pointer to the underlying GtkSeparatorToolItem.

native returns a pointer to the underlying GtkSeparatorToolItem .


func (v *SpinButton) native() *C.GtkSpinButton {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkSpinButton(p)
}

func ( v * SpinButton ) native ( ) * C . GtkSpinButton { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkSpinButton ( p ) }

// native returns a pointer to the underlying GtkSpinButton.

native returns a pointer to the underlying GtkSpinButton .


func (v *Spinner) native() *C.GtkSpinner {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkSpinner(p)
}

func ( v * Spinner ) native ( ) * C . GtkSpinner { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkSpinner ( p ) }

// native returns a pointer to the underlying GtkSpinner.

native returns a pointer to the underlying GtkSpinner .


func (v *Statusbar) native() *C.GtkStatusbar {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkStatusbar(p)
}

func ( v * Statusbar ) native ( ) * C . GtkStatusbar { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkStatusbar ( p ) }

// native returns a pointer to the underlying GtkStatusbar


func (v *Switch) native() *C.GtkSwitch {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkSwitch(p)
}

func ( v * Switch ) native ( ) * C . GtkSwitch { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkSwitch ( p ) }

// native returns a pointer to the underlying GtkSwitch.

native returns a pointer to the underlying GtkSwitch .


func (v *TextTag) native() *C.GtkTextTag {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkTextTag(p)
}

func ( v * TextTag ) native ( ) * C . GtkTextTag { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkTextTag ( p ) }

// native returns a pointer to the underlying GObject as a GtkTextTag.

native returns a pointer to the underlying GObject as a GtkTextTag .


func (v *TextTagTable) native() *C.GtkTextTagTable {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkTextTagTable(p)
}

func ( v * TextTagTable ) native ( ) * C . GtkTextTagTable { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkTextTagTable ( p ) }

// native returns a pointer to the underlying GObject as a GtkTextTagTable.

native returns a pointer to the underlying GObject as a GtkTextTagTable .


func (v *TextBuffer) native() *C.GtkTextBuffer {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkTextBuffer(p)
}

func ( v * TextBuffer ) native ( ) * C . GtkTextBuffer { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkTextBuffer ( p ) }

// native returns a pointer to the underlying GtkTextBuffer.

native returns a pointer to the underlying GtkTextBuffer .


func (v *TextBuffer) SelectRange(start, end *TextIter) {
	C.gtk_text_buffer_select_range(v.native(), (*C.GtkTextIter)(start), (*C.GtkTextIter)(end))
}

func ( v * TextBuffer ) SelectRange ( start , end * TextIter ) { C . gtk_text_buffer_select_range ( v . native ( ) , ( * C . GtkTextIter ) ( start ) , ( * C . GtkTextIter ) ( end ) ) }

// SelectRange is a wrapper around gtk_text_buffer_select_range.

SelectRange is a wrapper around gtk_text_buffer_select_range .


func (v *ToggleButton) native() *C.GtkToggleButton {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkToggleButton(p)
}

func ( v * ToggleButton ) native ( ) * C . GtkToggleButton { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkToggleButton ( p ) }

// native returns a pointer to the underlying GtkToggleButton.

native returns a pointer to the underlying GtkToggleButton .


func (v *Toolbar) native() *C.GtkToolbar {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkToolbar(p)
}

func ( v * Toolbar ) native ( ) * C . GtkToolbar { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkToolbar ( p ) }

// native returns a pointer to the underlying GtkToolbar.

native returns a pointer to the underlying GtkToolbar .


func (v *ToolButton) native() *C.GtkToolButton {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkToolButton(p)
}

func ( v * ToolButton ) native ( ) * C . GtkToolButton { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkToolButton ( p ) }

// native returns a pointer to the underlying GtkToolButton.

native returns a pointer to the underlying GtkToolButton .


func (v *ToggleToolButton) native() *C.GtkToggleToolButton {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkToggleToolButton(p)
}

func ( v * ToggleToolButton ) native ( ) * C . GtkToggleToolButton { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkToggleToolButton ( p ) }

// native returns a pointer to the underlying GtkToggleToolButton.

native returns a pointer to the underlying GtkToggleToolButton .


func (v *ToolItem) native() *C.GtkToolItem {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkToolItem(p)
}

func ( v * ToolItem ) native ( ) * C . GtkToolItem { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkToolItem ( p ) }

// native returns a pointer to the underlying GtkToolItem.

native returns a pointer to the underlying GtkToolItem .


func (v *TreeIter) native() *C.GtkTreeIter {
	if v == nil {
		return nil
	}
	return &v.GtkTreeIter
}

func ( v * TreeIter ) native ( ) * C . GtkTreeIter { if v == nil { return nil } return & v . GtkTreeIter }

// native returns a pointer to the underlying GtkTreeIter.

native returns a pointer to the underlying GtkTreeIter .


func (v *TreeModel) native() *C.GtkTreeModel {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkTreeModel(p)
}

func ( v * TreeModel ) native ( ) * C . GtkTreeModel { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkTreeModel ( p ) }

// native returns a pointer to the underlying GObject as a GtkTreeModel.

native returns a pointer to the underlying GObject as a GtkTreeModel .


func TreePathFromList(list *glib.List) *TreePath {
	if list == nil {
		return nil
	}
	return &TreePath{(*C.GtkTreePath)(list.Data().(unsafe.Pointer))}
}

func TreePathFromList ( list * glib . List ) * TreePath { if list == nil { return nil } return & TreePath { ( * C . GtkTreePath ) ( list . Data ( ) . ( unsafe . Pointer ) ) } }


func (v *TreePath) native() *C.GtkTreePath {
	if v == nil {
		return nil
	}
	return v.GtkTreePath
}

func ( v * TreePath ) native ( ) * C . GtkTreePath { if v == nil { return nil } return v . GtkTreePath }

// native returns a pointer to the underlying GtkTreePath.

native returns a pointer to the underlying GtkTreePath .


func (v *TreePath) GetIndices() []int {
	var depth C.gint
	var goindices []int
	var ginthelp C.gint
	indices := uintptr(unsafe.Pointer(C.gtk_tree_path_get_indices_with_depth(v.native(), &depth)))
	size := unsafe.Sizeof(ginthelp)
	for i := 0; i < int(depth); i++ {
		goind := int(*((*C.gint)(unsafe.Pointer(indices))))
		goindices = append(goindices, goind)
		indices += size
	}
	return goindices
}

func ( v * TreePath ) GetIndices ( ) [ ] int { var depth C . gint var goindices [ ] int var ginthelp C . gint indices := uintptr ( unsafe . Pointer ( C . gtk_tree_path_get_indices_with_depth ( v . native ( ) , & depth ) ) ) size := unsafe . Sizeof ( ginthelp ) for i := 0 ; i < int ( depth ) ; i ++ { goind := int ( * ( ( * C . gint ) ( unsafe . Pointer ( indices ) ) ) ) goindices = append ( goindices , goind ) indices += size } return goindices }

// GetIndices is a wrapper around gtk_tree_path_get_indices_with_depth


func (v *TreeSelection) native() *C.GtkTreeSelection {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkTreeSelection(p)
}

func ( v * TreeSelection ) native ( ) * C . GtkTreeSelection { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkTreeSelection ( p ) }

// native returns a pointer to the underlying GtkTreeSelection.

native returns a pointer to the underlying GtkTreeSelection .


func (v *TreeRowReference) GetPath() *TreePath {
	c := C.gtk_tree_row_reference_get_path(v.native())
	if c == nil {
		return nil
	}
	t := &TreePath{c}
	runtime.SetFinalizer(t, (*TreePath).free)
	return t
}

func ( v * TreeRowReference ) GetPath ( ) * TreePath { c := C . gtk_tree_row_reference_get_path ( v . native ( ) ) if c == nil { return nil } t := & TreePath { c } runtime . SetFinalizer ( t , ( * TreePath ) . free ) return t }

// GetPath is a wrapper around gtk_tree_row_reference_get_path.

GetPath is a wrapper around gtk_tree_row_reference_get_path .


func (v *TreeRowReference) GetModel() ITreeModel {
	c := C.gtk_tree_row_reference_get_model(v.native())
	if c == nil {
		return nil
	}
	m := wrapTreeModel(glib.Take(unsafe.Pointer(c)))
	return m
}

func ( v * TreeRowReference ) GetModel ( ) ITreeModel { c := C . gtk_tree_row_reference_get_model ( v . native ( ) ) if c == nil { return nil } m := wrapTreeModel ( glib . Take ( unsafe . Pointer ( c ) ) ) return m }

// GetModel is a wrapper around gtk_tree_row_reference_get_path.

GetModel is a wrapper around gtk_tree_row_reference_get_path .


func (v *TreeRowReference) Valid() bool {
	c := C.gtk_tree_row_reference_valid(v.native())
	return gobool(c)
}

func ( v * TreeRowReference ) Valid ( ) bool { c := C . gtk_tree_row_reference_valid ( v . native ( ) ) return gobool ( c ) }

// Valid is a wrapper around gtk_tree_row_reference_valid.

Valid is a wrapper around gtk_tree_row_reference_valid .


func (v *TreeStore) native() *C.GtkTreeStore {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkTreeStore(p)
}

func ( v * TreeStore ) native ( ) * C . GtkTreeStore { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkTreeStore ( p ) }

// native returns a pointer to the underlying GtkTreeStore.

native returns a pointer to the underlying GtkTreeStore .


func (v *TreeStore) Insert(parent *TreeIter, position int) *TreeIter {
	var ti C.GtkTreeIter
	var cParent *C.GtkTreeIter
	if parent != nil {
		cParent = parent.native()
	}
	C.gtk_tree_store_insert(v.native(), &ti, cParent, C.gint(position))
	iter := &TreeIter{ti}
	return iter
}

func ( v * TreeStore ) Insert ( parent * TreeIter , position int ) * TreeIter { var ti C . GtkTreeIter var cParent * C . GtkTreeIter if parent != nil { cParent = parent . native ( ) } C . gtk_tree_store_insert ( v . native ( ) , & ti , cParent , C . gint ( position ) ) iter := & TreeIter { ti } return iter }

// Insert is a wrapper around gtk_tree_store_insert


func SettingsGetDefault() (*Settings, error) {
	c := C.gtk_settings_get_default()
	if c == nil {
		return nil, nilPtrErr
	}

	return wrapSettings(glib.Take(unsafe.Pointer(c))), nil
}

func SettingsGetDefault ( ) ( * Settings , error ) { c := C . gtk_settings_get_default ( ) if c == nil { return nil , nilPtrErr } return wrapSettings ( glib . Take ( unsafe . Pointer ( c ) ) ) , nil }

//Get the global non window specific settings


func (v *TextMark) native() *C.GtkTextMark {
	if v == nil {
		return nil
	}
	return (*C.GtkTextMark)(v)
}

func ( v * TextMark ) native ( ) * C . GtkTextMark { if v == nil { return nil } return ( * C . GtkTextMark ) ( v ) }

// native returns a pointer to the underlying GtkTextMark.

native returns a pointer to the underlying GtkTextMark .


func (v *Pattern) native() *C.cairo_pattern_t {
	if v == nil {
		return nil
	}
	return v.pattern
}

func ( v * Pattern ) native ( ) * C . cairo_pattern_t { if v == nil { return nil } return v . pattern }

// native returns a pointer to the underlying cairo_pattern_t.

native returns a pointer to the underlying cairo_pattern_t .


func (v *Window) native() *C.GtkWindow {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkWindow(p)
}

func ( v * Window ) native ( ) * C . GtkWindow { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkWindow ( p ) }

// native returns a pointer to the underlying GtkWindow.

native returns a pointer to the underlying GtkWindow .


func (v Atom) native() C.GdkAtom {
	return C.toGdkAtom(unsafe.Pointer(uintptr(v)))
}

func ( v Atom ) native ( ) C . GdkAtom { return C . toGdkAtom ( unsafe . Pointer ( uintptr ( v ) ) ) }

// native returns the underlying GdkAtom.


func GdkAtomIntern(atomName string, onlyIfExists bool) Atom {
	cstr := C.CString(atomName)
	defer C.free(unsafe.Pointer(cstr))
	c := C.gdk_atom_intern((*C.gchar)(cstr), gbool(onlyIfExists))
	return Atom(uintptr(unsafe.Pointer(c)))
}

func GdkAtomIntern ( atomName string , onlyIfExists bool ) Atom { cstr := C . CString ( atomName ) defer C . free ( unsafe . Pointer ( cstr ) ) c := C . gdk_atom_intern ( ( * C . gchar ) ( cstr ) , gbool ( onlyIfExists ) ) return Atom ( uintptr ( unsafe . Pointer ( c ) ) ) }

// GdkAtomIntern is a wrapper around gdk_atom_intern


func (v *Device) native() *C.GdkDevice {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGdkDevice(p)
}

func ( v * Device ) native ( ) * C . GdkDevice { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGdkDevice ( p ) }

// native returns a pointer to the underlying GdkDevice.

native returns a pointer to the underlying GdkDevice .


func (v *Cursor) native() *C.GdkCursor {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGdkCursor(p)
}

func ( v * Cursor ) native ( ) * C . GdkCursor { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGdkCursor ( p ) }

// native returns a pointer to the underlying GdkCursor.

native returns a pointer to the underlying GdkCursor .


func (v *DeviceManager) native() *C.GdkDeviceManager {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGdkDeviceManager(p)
}

func ( v * DeviceManager ) native ( ) * C . GdkDeviceManager { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGdkDeviceManager ( p ) }

// native returns a pointer to the underlying GdkDeviceManager.

native returns a pointer to the underlying GdkDeviceManager .


func (v *Display) native() *C.GdkDisplay {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGdkDisplay(p)
}

func ( v * Display ) native ( ) * C . GdkDisplay { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGdkDisplay ( p ) }

// native returns a pointer to the underlying GdkDisplay.

native returns a pointer to the underlying GdkDisplay .


func (v *DragContext) native() *C.GdkDragContext {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGdkDragContext(p)
}

func ( v * DragContext ) native ( ) * C . GdkDragContext { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGdkDragContext ( p ) }

// native returns a pointer to the underlying GdkDragContext.

native returns a pointer to the underlying GdkDragContext .


func (v *Event) native() *C.GdkEvent {
	if v == nil {
		return nil
	}
	return v.GdkEvent
}

func ( v * Event ) native ( ) * C . GdkEvent { if v == nil { return nil } return v . GdkEvent }

// native returns a pointer to the underlying GdkEvent.

native returns a pointer to the underlying GdkEvent .


func (v *EventButton) XRoot() float64 {
	c := v.native().x_root
	return float64(c)
}

func ( v * EventButton ) XRoot ( ) float64 { c := v . native ( ) . x_root return float64 ( c ) }

// XRoot returns the x coordinate of the pointer relative to the root of the screen.

XRoot returns the x coordinate of the pointer relative to the root of the screen .


func (v *EventButton) YRoot() float64 {
	c := v.native().y_root
	return float64(c)
}

func ( v * EventButton ) YRoot ( ) float64 { c := v . native ( ) . y_root return float64 ( c ) }

// YRoot returns the y coordinate of the pointer relative to the root of the screen.

YRoot returns the y coordinate of the pointer relative to the root of the screen .


func (c *RGBA) SetColors(r, g, b, a float64) {
	c.rgba.red = C.gdouble(r)
	c.rgba.green = C.gdouble(g)
	c.rgba.blue = C.gdouble(b)
	c.rgba.alpha = C.gdouble(a)
}

func ( c * RGBA ) SetColors ( r , g , b , a float64 ) { c . rgba . red = C . gdouble ( r ) c . rgba . green = C . gdouble ( g ) c . rgba . blue = C . gdouble ( b ) c . rgba . alpha = C . gdouble ( a ) }

// SetColors sets all colors values in the RGBA.

SetColors sets all colors values in the RGBA .


func (v *Window) native() *C.GdkWindow {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGdkWindow(p)
}

func ( v * Window ) native ( ) * C . GdkWindow { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGdkWindow ( p ) }

// native returns a pointer to the underlying GdkWindow.

native returns a pointer to the underlying GdkWindow .


func ClosureNew(f interface{}, marshalData ...interface{}) (*C.GClosure, error) {
	// Create a reflect.Value from f.  This is called when the
	// returned GClosure runs.
	rf := reflect.ValueOf(f)

	// Create closure context which points to the reflected func.
	cc := closureContext{rf: rf}

	// Closures can only be created from funcs.
	if rf.Type().Kind() != reflect.Func {
		return nil, errors.New("value is not a func")
	}

	if len(marshalData) > 0 {
		cc.userData = reflect.ValueOf(marshalData[0])
	}

	c := C._g_closure_new()

	// Associate the GClosure with rf.  rf will be looked up in this
	// map by the closure when the closure runs.
	closures.Lock()
	closures.m[c] = cc
	closures.Unlock()

	return c, nil
}

// ClosureNew creates a new GClosure and adds its callback function
// to the internally-maintained map. It's exported for visibility to other
// gotk3 packages and shouldn't be used in application code.

ClosureNew creates a new GClosure and adds its callback function to the internally - maintained map . It s exported for visibility to other gotk3 packages and shouldn t be used in application code .


func (v *ColorChooser) native() *C.GtkColorChooser {
	if v == nil || v.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(v.GObject)
	return C.toGtkColorChooser(p)
}

func ( v * ColorChooser ) native ( ) * C . GtkColorChooser { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkColorChooser ( p ) }

// native returns a pointer to the underlying GtkColorChooser.

native returns a pointer to the underlying GtkColorChooser .


func (v *ColorChooserDialog) native() *C.GtkColorChooserDialog {
	if v == nil || v.GObject == nil {
		return nil
	}

	p := unsafe.Pointer(v.GObject)
	return C.toGtkColorChooserDialog(p)
}

func ( v * ColorChooserDialog ) native ( ) * C . GtkColorChooserDialog { if v == nil || v . GObject == nil { return nil } p := unsafe . Pointer ( v . GObject ) return C . toGtkColorChooserDialog ( p ) }

// native returns a pointer to the underlying GtkColorChooserButton.

native returns a pointer to the underlying GtkColorChooserButton .


func (v *Source) native() *C.GSource {
	if v == nil {
		return nil
	}
	return (*C.GSource)(v)
}

func ( v * Source ) native ( ) * C . GSource { if v == nil { return nil } return ( * C . GSource ) ( v ) }

// native returns a pointer to the underlying GSource.

native returns a pointer to the underlying GSource .


func (v *Context) Translate(tx, ty float64) {
	C.cairo_translate(v.native(), C.double(tx), C.double(ty))
}

func ( v * Context ) Translate ( tx , ty float64 ) { C . cairo_translate ( v . native ( ) , C . double ( tx ) , C . double ( ty ) ) }

// Translate is a wrapper around cairo_translate.

Translate is a wrapper around cairo_translate .


func (v *Context) Scale(sx, sy float64) {
	C.cairo_scale(v.native(), C.double(sx), C.double(sy))
}

func ( v * Context ) Scale ( sx , sy float64 ) { C . cairo_scale ( v . native ( ) , C . double ( sx ) , C . double ( sy ) ) }

// Scale is a wrapper around cairo_scale.


func (v *Context) Rotate(angle float64) {
	C.cairo_rotate(v.native(), C.double(angle))
}

func ( v * Context ) Rotate ( angle float64 ) { C . cairo_rotate ( v . native ( ) , C . double ( angle ) ) }

// Rotate is a wrapper around cairo_rotate.

Rotate is a wrapper around cairo_rotate .


func (v *Context) Transform(matrix *Matrix) {
	C.cairo_transform(v.native(), matrix.native())
}

func ( v * Context ) Transform ( matrix * Matrix ) { C . cairo_transform ( v . native ( ) , matrix . native ( ) ) }

// Transform is a wrapper around cairo_transform.

Transform is a wrapper around cairo_transform .


func (v *Context) SetMatrix(matrix *Matrix) {
	C.cairo_set_matrix(v.native(), matrix.native())
}

func ( v * Context ) SetMatrix ( matrix * Matrix ) { C . cairo_set_matrix ( v . native ( ) , matrix . native ( ) ) }

// SetMatrix is a wrapper around cairo_set_matrix.

SetMatrix is a wrapper around cairo_set_matrix .


func (v *Context) GetMatrix() *Matrix {
	var matrix C.cairo_matrix_t
	C.cairo_get_matrix(v.native(), &matrix)
	return &Matrix{
		Xx: float64(matrix.xx),
		Yx: float64(matrix.yx),
		Xy: float64(matrix.xy),
		Yy: float64(matrix.yy),
		X0: float64(matrix.x0),
		Y0: float64(matrix.y0),
	}
}

func ( v * Context ) GetMatrix ( ) * Matrix { var matrix C . cairo_matrix_t C . cairo_get_matrix ( v . native ( ) , & matrix ) return & Matrix { Xx : float64 ( matrix . xx ) , Yx : float64 ( matrix . yx ) , Xy : float64 ( matrix . xy ) , Yy : float64 ( matrix . yy ) , X0 : float64 ( matrix . x0 ) , Y0 : float64 ( matrix . y0 ) , } }

// GetMatrix is a wrapper around cairo_get_matrix.

GetMatrix is a wrapper around cairo_get_matrix .


func (v *Context) UserToDevice(x, y float64) (float64, float64) {
	C.cairo_user_to_device(v.native(), (*C.double)(&x), (*C.double)(&y))
	return x, y
}

func ( v * Context ) UserToDevice ( x , y float64 ) ( float64 , float64 ) { C . cairo_user_to_device ( v . native ( ) , ( * C . double ) ( & x ) , ( * C . double ) ( & y ) ) return x , y }

// UserToDevice is a wrapper around cairo_user_to_device.

UserToDevice is a wrapper around cairo_user_to_device .


func (v *Context) UserToDeviceDistance(dx, dy float64) (float64, float64) {
	C.cairo_user_to_device_distance(v.native(), (*C.double)(&dx), (*C.double)(&dy))
	return dx, dy
}

func ( v * Context ) UserToDeviceDistance ( dx , dy float64 ) ( float64 , float64 ) { C . cairo_user_to_device_distance ( v . native ( ) , ( * C . double ) ( & dx ) , ( * C . double ) ( & dy ) ) return dx , dy }

// UserToDeviceDistance is a wrapper around cairo_user_to_device_distance.

UserToDeviceDistance is a wrapper around cairo_user_to_device_distance .


func (v *Context) DeviceToUser(x, y float64) (float64, float64) {
	C.cairo_device_to_user(v.native(), (*C.double)(&x), (*C.double)(&y))
	return x, y
}

func ( v * Context ) DeviceToUser ( x , y float64 ) ( float64 , float64 ) { C . cairo_device_to_user ( v . native ( ) , ( * C . double ) ( & x ) , ( * C . double ) ( & y ) ) return x , y }

// DeviceToUser  is a wrapper around cairo_device_to_user.

DeviceToUser is a wrapper around cairo_device_to_user .


func (v *Context) DeviceToUserDistance(x, y float64) (float64, float64) {
	C.cairo_device_to_user_distance(v.native(), (*C.double)(&x), (*C.double)(&y))
	return x, y
}

func ( v * Context ) DeviceToUserDistance ( x , y float64 ) ( float64 , float64 ) { C . cairo_device_to_user_distance ( v . native ( ) , ( * C . double ) ( & x ) , ( * C . double ) ( & y ) ) return x , y }

// DeviceToUserDistance is a wrapper around cairo_device_to_user_distance.

DeviceToUserDistance is a wrapper around cairo_device_to_user_distance .


func (s *Sprite) Draw(screen *ebiten.Image, dx, dy int, alpha float64) {
	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(float64(s.x+dx), float64(s.y+dy))
	op.ColorM.Scale(1, 1, 1, alpha)
	screen.DrawImage(s.image, op)
	screen.DrawImage(s.image, op)
}

func ( s * Sprite ) Draw ( screen * ebiten . Image , dx , dy int , alpha float64 ) { op := & ebiten . DrawImageOptions { } op . GeoM . Translate ( float64 ( s . x + dx ) , float64 ( s . y + dy ) ) op . ColorM . Scale ( 1 , 1 , 1 , alpha ) screen . DrawImage ( s . image , op ) screen . DrawImage ( s . image , op ) }


func (s *Stream) Length() int64 {
	if s.resampling != nil {
		return s.resampling.Length()
	}
	return s.orig.Length()
}

func ( s * Stream ) Length ( ) int64 { if s . resampling != nil { return s . resampling . Length ( ) } return s . orig . Length ( ) }

// Length returns the size of decoded stream in bytes.

Length returns the size of decoded stream in bytes .


func Decode(context *audio.Context, src audio.ReadSeekCloser) (*Stream, error) {
	d, err := mp3.NewDecoder(src)
	if err != nil {
		return nil, err
	}

	var r *convert.Resampling
	if d.SampleRate() != context.SampleRate() {
		r = convert.NewResampling(d, d.Length(), d.SampleRate(), context.SampleRate())
	}
	s := &Stream{
		orig:       d,
		resampling: r,
		toClose:    src,
	}
	runtime.SetFinalizer(s, (*Stream).Close)
	return s, nil
}

func Decode ( context * audio . Context , src audio . ReadSeekCloser ) ( * Stream , error ) { d , err := mp3 . NewDecoder ( src ) if err != nil { return nil , err } var r * convert . Resampling if d . SampleRate ( ) != context . SampleRate ( ) { r = convert . NewResampling ( d , d . Length ( ) , d . SampleRate ( ) , context . SampleRate ( ) ) } s := & Stream { orig : d , resampling : r , toClose : src , } runtime . SetFinalizer ( s , ( * Stream ) . Close ) return s , nil }

// Decode decodes MP3 source and returns a decoded stream.
//
// Decode returns error when decoding fails or IO error happens.
//
// Decode automatically resamples the stream to fit with the audio context if necessary.
//
// Decode takes the ownership of src, and Stream's Close function closes src.

Decode decodes MP3 source and returns a decoded stream . Decode returns error when decoding fails or IO error happens . Decode automatically resamples the stream to fit with the audio context if necessary . Decode takes the ownership of src and Stream s Close function closes src .


func IsMouseButtonPressed(mouseButton MouseButton) bool {
	return uiDriver().Input().IsMouseButtonPressed(driver.MouseButton(mouseButton))
}

func IsMouseButtonPressed ( mouseButton MouseButton ) bool { return uiDriver ( ) . Input ( ) . IsMouseButtonPressed ( driver . MouseButton ( mouseButton ) ) }

// IsMouseButtonPressed returns a boolean indicating whether mouseButton is pressed.
//
// IsMouseButtonPressed is concurrent-safe.
//
// Note that touch events not longer affect IsMouseButtonPressed's result as of 1.4.0-alpha.
// Use Touches instead.

IsMouseButtonPressed returns a boolean indicating whether mouseButton is pressed . IsMouseButtonPressed is concurrent - safe . Note that touch events not longer affect IsMouseButtonPressed s result as of 1 . 4 . 0 - alpha . Use Touches instead .


func Touches() []Touch {
	var ts []Touch
	for _, id := range TouchIDs() {
		x, y := TouchPosition(id)
		ts = append(ts, &touch{
			id: id,
			x:  x,
			y:  y,
		})
	}
	return ts
}

func Touches ( ) [ ] Touch { var ts [ ] Touch for _ , id := range TouchIDs ( ) { x , y := TouchPosition ( id ) ts = append ( ts , & touch { id : id , x : x , y : y , } ) } return ts }

// Touches is deprecated as of 1.7.0. Use TouchIDs instead.

Touches is deprecated as of 1 . 7 . 0 . Use TouchIDs instead .


func paeth(a, b, c uint8) uint8 {
	// This is an optimized version of the sample code in the PNG spec.
	// For example, the sample code starts with:
	//	p := int(a) + int(b) - int(c)
	//	pa := abs(p - int(a))
	// but the optimized form uses fewer arithmetic operations:
	//	pa := int(b) - int(c)
	//	pa = abs(pa)
	pc := int(c)
	pa := int(b) - pc
	pb := int(a) - pc
	pc = abs(pa + pb)
	pa = abs(pa)
	pb = abs(pb)
	if pa <= pb && pa <= pc {
		return a
	} else if pb <= pc {
		return b
	}
	return c
}

// paeth implements the Paeth filter function, as per the PNG specification.

paeth implements the Paeth filter function as per the PNG specification .


func filterPaeth(cdat, pdat []byte, bytesPerPixel int) {
	var a, b, c, pa, pb, pc int
	for i := 0; i < bytesPerPixel; i++ {
		a, c = 0, 0
		for j := i; j < len(cdat); j += bytesPerPixel {
			b = int(pdat[j])
			pa = b - c
			pb = a - c
			pc = abs(pa + pb)
			pa = abs(pa)
			pb = abs(pb)
			if pa <= pb && pa <= pc {
				// No-op.
			} else if pb <= pc {
				a = b
			} else {
				a = c
			}
			a += int(cdat[j])
			a &= 0xff
			cdat[j] = uint8(a)
			c = b
		}
	}
}

func
filterPaeth
(
cdat
,
pdat
[
]
byte
,
bytesPerPixel
int
)
{
var
a
,
b
,
c
,
pa
,
pb
,
pc
int
for
i
:=
0
;
i
<
bytesPerPixel
;
i
++
{
a
,
c
=
0
,
0
for
j
:=
i
;
j
<
len
(
cdat
)
;
j
+=
bytesPerPixel
{
b
=
int
(
pdat
[
j
]
)
pa
=
b
c
pb
=
a
c
pc
=
abs
(
pa
+
pb
)
pa
=
abs
(
pa
)
pb
=
abs
(
pb
)
if
pa
<=
pb
&&
pa
<=
pc
{
// No-op.
}
else
if
pb
<=
pc
{
a
=
b
}
else
{
a
=
c
}
a
+=
int
(
cdat
[
j
]
)
a
&=
0xff
cdat
[
j
]
=
uint8
(
a
)
c
=
b
}
}
}

// filterPaeth applies the Paeth filter to the cdat slice.
// cdat is the current row's data, pdat is the previous row's data.

filterPaeth applies the Paeth filter to the cdat slice . cdat is the current row s data pdat is the previous row s data .


func MipmapLevel(det float32) int {
	if math.IsNaN(float64(det)) {
		panic("graphicsutil: det must be finite")
	}
	if det == 0 {
		return -1
	}

	d := math.Abs(float64(det))
	level := 0
	for d < 0.25 {
		level++
		d *= 4
	}
	return level
}

func MipmapLevel ( det float32 ) int { if math . IsNaN ( float64 ( det ) ) { panic ( " " ) } if det == 0 { return - 1 } d := math . Abs ( float64 ( det ) ) level := 0 for d < 0.25 { level ++ d *= 4 } return level }

// MipmapLevel returns an appropriate mipmap level for the given determinant of a geometry matrix.
//
// MipmapLevel returns -1 if det is 0.
//
// MipmapLevel panics if det is NaN.

MipmapLevel returns an appropriate mipmap level for the given determinant of a geometry matrix . MipmapLevel returns - 1 if det is 0 . MipmapLevel panics if det is NaN .


func hideConsoleWindowOnWindows() {
	pid, err := getCurrentProcessId()
	if err != nil {
		// Ignore errors because:
		// 1. It is not critical if the console can't be hid.
		// 2. There is nothing to do when errors happen.
		return
	}
	w, err := getConsoleWindow()
	if err != nil {
		// Ignore errors
		return
	}
	// Get the process ID of the console's creator.
	cpid, err := getWindowThreadProcessId(w)
	if err != nil {
		// Ignore errors
		return
	}
	if pid == cpid {
		// The current process created its own console. Hide this.
		showWindowAsync(w, windows.SW_HIDE)
	}
}

// hideConsoleWindowOnWindows will hide the console window that is showing when
// compiling on Windows without specifying the '-ldflags "-Hwindowsgui"' flag.

hideConsoleWindowOnWindows will hide the console window that is showing when compiling on Windows without specifying the - ldflags - Hwindowsgui flag .


func DepthMask(flag bool) {
	C.glowDepthMask(gpDepthMask, (C.GLboolean)(boolToInt(flag)))
}

func DepthMask ( flag bool ) { C . glowDepthMask ( gpDepthMask , ( C . GLboolean ) ( boolToInt ( flag ) ) ) }

// enable or disable writing into the depth buffer


func EdgeFlag(flag bool) {
	C.glowEdgeFlag(gpEdgeFlag, (C.GLboolean)(boolToInt(flag)))
}

func EdgeFlag ( flag bool ) { C . glowEdgeFlag ( gpEdgeFlag , ( C . GLboolean ) ( boolToInt ( flag ) ) ) }

// flag edges as either boundary or nonboundary


func TexImage3D(target uint32, level int32, internalformat int32, width int32, height int32, depth int32, border int32, format uint32, xtype uint32, pixels unsafe.Pointer) {
	C.glowTexImage3D(gpTexImage3D, (C.GLenum)(target), (C.GLint)(level), (C.GLint)(internalformat), (C.GLsizei)(width), (C.GLsizei)(height), (C.GLsizei)(depth), (C.GLint)(border), (C.GLenum)(format), (C.GLenum)(xtype), pixels)
}

func TexImage3D ( target uint32 , level int32 , internalformat int32 , width int32 , height int32 , depth int32 , border int32 , format uint32 , xtype uint32 , pixels unsafe . Pointer ) { C . glowTexImage3D ( gpTexImage3D , ( C . GLenum ) ( target ) , ( C . GLint ) ( level ) , ( C . GLint ) ( internalformat ) , ( C . GLsizei ) ( width ) , ( C . GLsizei ) ( height ) , ( C . GLsizei ) ( depth ) , ( C . GLint ) ( border ) , ( C . GLenum ) ( format ) , ( C . GLenum ) ( xtype ) , pixels ) }

// specify a three-dimensional texture image

specify a three - dimensional texture image


func (i *Image) QuadVertices(sx0, sy0, sx1, sy1 int, a, b, c, d, tx, ty float32, cr, cg, cb, ca float32) []float32 {
	if i.backend == nil {
		i.allocate(true)
	}
	ox, oy, _, _ := i.region()
	return i.backend.restorable.QuadVertices(sx0+ox, sy0+oy, sx1+ox, sy1+oy, a, b, c, d, tx, ty, cr, cg, cb, ca)
}

func ( i * Image ) QuadVertices ( sx0 , sy0 , sx1 , sy1 int , a , b , c , d , tx , ty float32 , cr , cg , cb , ca float32 ) [ ] float32 { if i . backend == nil { i . allocate ( true ) } ox , oy , _ , _ := i . region ( ) return i . backend . restorable . QuadVertices ( sx0 + ox , sy0 + oy , sx1 + ox , sy1 + oy , a , b , c , d , tx , ty , cr , cg , cb , ca ) }

// QuadVertices returns the vertices for rendering a quad.
//
// QuadVertices is highly optimized for rendering quads, and that's the most significant difference from
// PutVertices.

QuadVertices returns the vertices for rendering a quad . QuadVertices is highly optimized for rendering quads and that s the most significant difference from PutVertices .


func (i *Image) PutVertex(dest []float32, dx, dy, sx, sy float32, bx0, by0, bx1, by1 float32, cr, cg, cb, ca float32) {
	if i.backend == nil {
		i.allocate(true)
	}
	ox, oy, _, _ := i.region()
	oxf, oyf := float32(ox), float32(oy)
	i.backend.restorable.PutVertex(dest, dx, dy, sx+oxf, sy+oyf, bx0+oxf, by0+oyf, bx1+oxf, by1+oyf, cr, cg, cb, ca)
}

func ( i * Image ) PutVertex ( dest [ ] float32 , dx , dy , sx , sy float32 , bx0 , by0 , bx1 , by1 float32 , cr , cg , cb , ca float32 ) { if i . backend == nil { i . allocate ( true ) } ox , oy , _ , _ := i . region ( ) oxf , oyf := float32 ( ox ) , float32 ( oy ) i . backend . restorable . PutVertex ( dest , dx , dy , sx + oxf , sy + oyf , bx0 + oxf , by0 + oyf , bx1 + oxf , by1 + oyf , cr , cg , cb , ca ) }

// PutVertices puts the given dest with vertices that can be passed to DrawTriangles.

PutVertices puts the given dest with vertices that can be passed to DrawTriangles .


func scaleUpdater() {
	for {
		s := getscale(0, 0)
		atomic.StoreUint64(&cachedScale, math.Float64bits(s))
		time.Sleep(cacheUpdateWait)
	}
}

func scaleUpdater ( ) { for { s := getscale ( 0 , 0 ) atomic . StoreUint64 ( & cachedScale , math . Float64bits ( s ) ) time . Sleep ( cacheUpdateWait ) } }

// run as goroutine. Will keep the desktop scale up to date.
// This can be removed once the scale change event is implemented in GLFW 3.3

run as goroutine . Will keep the desktop scale up to date . This can be removed once the scale change event is implemented in GLFW 3 . 3


func NewBoard(size int) (*Board, error) {
	b := &Board{
		size:  size,
		tiles: map[*Tile]struct{}{},
	}
	for i := 0; i < 2; i++ {
		if err := addRandomTile(b.tiles, b.size); err != nil {
			return nil, err
		}
	}
	return b, nil
}

func NewBoard ( size int ) ( * Board , error ) { b := & Board { size : size , tiles : map [ * Tile ] struct { } { } , } for i := 0 ; i < 2 ; i ++ { if err := addRandomTile ( b . tiles , b . size ) ; err != nil { return nil , err } } return b , nil }

// NewBoard generates a new Board with giving a size.

NewBoard generates a new Board with giving a size .


func (b *Board) Update(input *Input) error {
	for t := range b.tiles {
		if err := t.Update(); err != nil {
			return err
		}
	}
	if 0 < len(b.tasks) {
		t := b.tasks[0]
		if err := t(); err == taskTerminated {
			b.tasks = b.tasks[1:]
		} else if err != nil {
			return err
		}
		return nil
	}
	if dir, ok := input.Dir(); ok {
		if err := b.Move(dir); err != nil {
			return err
		}
	}
	return nil
}

func ( b * Board ) Update ( input * Input ) error { for t := range b . tiles { if err := t . Update ( ) ; err != nil { return err } } if 0 < len ( b . tasks ) { t := b . tasks [ 0 ] if err := t ( ) ; err == taskTerminated { b . tasks = b . tasks [ 1 : ] } else if err != nil { return err } return nil } if dir , ok := input . Dir ( ) ; ok { if err := b . Move ( dir ) ; err != nil { return err } } return nil }


func (b *Board) Move(dir Dir) error {
	for t := range b.tiles {
		t.stopAnimation()
	}
	if !MoveTiles(b.tiles, b.size, dir) {
		return nil
	}
	b.tasks = append(b.tasks, func() error {
		for t := range b.tiles {
			if t.IsMoving() {
				return nil
			}
		}
		return taskTerminated
	})
	b.tasks = append(b.tasks, func() error {
		nextTiles := map[*Tile]struct{}{}
		for t := range b.tiles {
			if t.IsMoving() {
				panic("not reach")
			}
			if t.next.value != 0 {
				panic("not reach")
			}
			if t.current.value == 0 {
				continue
			}
			nextTiles[t] = struct{}{}
		}
		b.tiles = nextTiles
		if err := addRandomTile(b.tiles, b.size); err != nil {
			return err
		}
		return taskTerminated
	})
	return nil
}

func ( b * Board ) Move ( dir Dir ) error { for t := range b . tiles { t . stopAnimation ( ) } if ! MoveTiles ( b . tiles , b . size , dir ) { return nil } b . tasks = append ( b . tasks , func ( ) error { for t := range b . tiles { if t . IsMoving ( ) { return nil } } return taskTerminated } ) b . tasks = append ( b . tasks , func ( ) error { nextTiles := map [ * Tile ] struct { } { } for t := range b . tiles { if t . IsMoving ( ) { panic ( " " ) } if t . next . value != 0 { panic ( " " ) } if t . current . value == 0 { continue } nextTiles [ t ] = struct { } { } } b . tiles = nextTiles if err := addRandomTile ( b . tiles , b . size ) ; err != nil { return err } return taskTerminated } ) return nil }


func (b *Board) Size() (int, int) {
	x := b.size*tileSize + (b.size+1)*tileMargin
	y := x
	return x, y
}

func ( b * Board ) Size ( ) ( int , int ) { x := b . size * tileSize + ( b . size + 1 ) * tileMargin y := x return x , y }


func (b *Board) Draw(boardImage *ebiten.Image) {
	boardImage.Fill(frameColor)
	for j := 0; j < b.size; j++ {
		for i := 0; i < b.size; i++ {
			v := 0
			op := &ebiten.DrawImageOptions{}
			x := i*tileSize + (i+1)*tileMargin
			y := j*tileSize + (j+1)*tileMargin
			op.GeoM.Translate(float64(x), float64(y))
			r, g, b, a := colorToScale(tileBackgroundColor(v))
			op.ColorM.Scale(r, g, b, a)
			boardImage.DrawImage(tileImage, op)
		}
	}
	animatingTiles := map[*Tile]struct{}{}
	nonAnimatingTiles := map[*Tile]struct{}{}
	for t := range b.tiles {
		if t.IsMoving() {
			animatingTiles[t] = struct{}{}
		} else {
			nonAnimatingTiles[t] = struct{}{}
		}
	}
	for t := range nonAnimatingTiles {
		t.Draw(boardImage)
	}
	for t := range animatingTiles {
		t.Draw(boardImage)
	}
}

func ( b * Board ) Draw ( boardImage * ebiten . Image ) { boardImage . Fill ( frameColor ) for j := 0 ; j < b . size ; j ++ { for i := 0 ; i < b . size ; i ++ { v := 0 op := & ebiten . DrawImageOptions { } x := i * tileSize + ( i + 1 ) * tileMargin y := j * tileSize + ( j + 1 ) * tileMargin op . GeoM . Translate ( float64 ( x ) , float64 ( y ) ) r , g , b , a := colorToScale ( tileBackgroundColor ( v ) ) op . ColorM . Scale ( r , g , b , a ) boardImage . DrawImage ( tileImage , op ) } } animatingTiles := map [ * Tile ] struct { } { } nonAnimatingTiles := map [ * Tile ] struct { } { } for t := range b . tiles { if t . IsMoving ( ) { animatingTiles [ t ] = struct { } { } } else { nonAnimatingTiles [ t ] = struct { } { } } } for t := range nonAnimatingTiles { t . Draw ( boardImage ) } for t := range animatingTiles { t . Draw ( boardImage ) } }

// Draw draws the board to the given boardImage.

Draw draws the board to the given boardImage .


func ClearIndex(c float32) {
	syscall.Syscall(gpClearIndex, 1, uintptr(math.Float32bits(c)), 0, 0)
}

func ClearIndex ( c float32 ) { syscall . Syscall ( gpClearIndex , 1 , uintptr ( math . Float32bits ( c ) ) , 0 , 0 ) }

// specify the clear value for the color index buffers


func CreateProgram() uint32 {
	ret, _, _ := syscall.Syscall(gpCreateProgram, 0, 0, 0, 0)
	return (uint32)(ret)
}

func CreateProgram ( ) uint32 { ret , _ , _ := syscall . Syscall ( gpCreateProgram , 0 , 0 , 0 , 0 ) return ( uint32 ) ( ret ) }


func DebugMessageCallback(callback unsafe.Pointer, userParam unsafe.Pointer) {
	syscall.Syscall(gpDebugMessageCallback, 2, syscall.NewCallback(callback), uintptr(userParam), 0)
}

func DebugMessageCallback ( callback unsafe . Pointer , userParam unsafe . Pointer ) { syscall . Syscall ( gpDebugMessageCallback , 2 , syscall . NewCallback ( callback ) , uintptr ( userParam ) , 0 ) }

// specify a callback to receive debugging messages from the GL
// Parameter callback has type C.GLDEBUGPROC.

specify a callback to receive debugging messages from the GL Parameter callback has type C . GLDEBUGPROC .


func GetError() uint32 {
	ret, _, _ := syscall.Syscall(gpGetError, 0, 0, 0, 0)
	return (uint32)(ret)
}

func GetError ( ) uint32 { ret , _ , _ := syscall . Syscall ( gpGetError , 0 , 0 , 0 , 0 ) return ( uint32 ) ( ret ) }


func GetGraphicsResetStatus() uint32 {
	ret, _, _ := syscall.Syscall(gpGetGraphicsResetStatus, 0, 0, 0, 0)
	return (uint32)(ret)
}

func GetGraphicsResetStatus ( ) uint32 { ret , _ , _ := syscall . Syscall ( gpGetGraphicsResetStatus , 0 , 0 , 0 , 0 ) return ( uint32 ) ( ret ) }

// check if the rendering context has not been lost due to software or hardware issues


func LineWidth(width float32) {
	syscall.Syscall(gpLineWidth, 1, uintptr(math.Float32bits(width)), 0, 0)
}

func LineWidth ( width float32 ) { syscall . Syscall ( gpLineWidth , 1 , uintptr ( math . Float32bits ( width ) ) , 0 , 0 ) }

// specify the width of rasterized lines


func PassThrough(token float32) {
	syscall.Syscall(gpPassThrough, 1, uintptr(math.Float32bits(token)), 0, 0)
}

func PassThrough ( token float32 ) { syscall . Syscall ( gpPassThrough , 1 , uintptr ( math . Float32bits ( token ) ) , 0 , 0 ) }

// place a marker in the feedback buffer


func PointSize(size float32) {
	syscall.Syscall(gpPointSize, 1, uintptr(math.Float32bits(size)), 0, 0)
}

func PointSize ( size float32 ) { syscall . Syscall ( gpPointSize , 1 , uintptr ( math . Float32bits ( size ) ) , 0 , 0 ) }

// specify the diameter of rasterized points


func (c *Context) IsReady() bool {
	c.m.Lock()
	r := c.ready
	c.m.Unlock()
	return r
}

func ( c * Context ) IsReady ( ) bool { c . m . Lock ( ) r := c . ready c . m . Unlock ( ) return r }

// IsReady returns a boolean value indicating whether the audio is ready or not.
//
// On some browsers, user interaction like click or pressing keys is required to start audio.

IsReady returns a boolean value indicating whether the audio is ready or not . On some browsers user interaction like click or pressing keys is required to start audio .


func NewPlayerFromBytes(context *Context, src []byte) (*Player, error) {
	b := BytesReadSeekCloser(src)
	p, err := NewPlayer(context, b)
	if err != nil {
		// Errors should never happen.
		panic(fmt.Sprintf("audio: %v at NewPlayerFromBytes", err))
	}
	return p, nil
}

func
NewPlayerFromBytes
(
context
*
Context
,
src
[
]
byte
)
(
*
Player
,
error
)
{
b
:=
BytesReadSeekCloser
(
src
)
p
,
err
:=
NewPlayer
(
context
,
b
)
if
err
!=
{
// Errors should never happen.
panic
(
fmt
.
Sprintf
(
"
"
,
err
)
)
}
return
p
,
}

// NewPlayerFromBytes creates a new player with the given bytes.
//
// As opposed to NewPlayer, you don't have to care if src is already used by another player or not.
// src can be shared by multiple players.
//
// The format of src should be same as noted at NewPlayer.
//
// NewPlayerFromBytes's error is always nil as of 1.5.0-alpha.

NewPlayerFromBytes creates a new player with the given bytes . As opposed to NewPlayer you don t have to care if src is already used by another player or not . src can be shared by multiple players . The format of src should be same as noted at NewPlayer . NewPlayerFromBytes s error is always nil as of 1 . 5 . 0 - alpha .


func (p *Player) Close() error {
	runtime.SetFinalizer(p, nil)
	return p.p.Close()
}

func ( p * Player ) Close ( ) error { runtime . SetFinalizer ( p , nil ) return p . p . Close ( ) }

// Close closes the stream.
//
// When closing, the stream owned by the player will also be closed by calling its Close.
// This means that the source stream passed via NewPlayer will also be closed.
//
// Close returns error when closing the source returns error.

Close closes the stream . When closing the stream owned by the player will also be closed by calling its Close . This means that the source stream passed via NewPlayer will also be closed . Close returns error when closing the source returns error .


func (p *Player) Seek(offset time.Duration) error {
	return p.p.Seek(offset)
}

func ( p * Player ) Seek ( offset time . Duration ) error { return p . p . Seek ( offset ) }

// Seek seeks the position with the given offset.
//
// The passed source to NewPlayer must be io.Seeker, or Seek panics.
//
// Seek returns error when seeking the source stream returns error.

Seek seeks the position with the given offset . The passed source to NewPlayer must be io . Seeker or Seek panics . Seek returns error when seeking the source stream returns error .


func (d *decoder) decode() (image.Image, error) {
	r, err := zlib.NewReader(d)
	if err != nil {
		return nil, err
	}
	defer r.Close()
	var img image.Image
	if d.interlace == itNone {
		img, err = d.readImagePass(r, 0, false)
		if err != nil {
			return nil, err
		}
	} else if d.interlace == itAdam7 {
		// Allocate a blank image of the full size.
		img, err = d.readImagePass(nil, 0, true)
		if err != nil {
			return nil, err
		}
		for pass := 0; pass < 7; pass++ {
			imagePass, err := d.readImagePass(r, pass, false)
			if err != nil {
				return nil, err
			}
			if imagePass != nil {
				d.mergePassInto(img, imagePass, pass)
			}
		}
	}

	// Check for EOF, to verify the zlib checksum.
	n := 0
	for i := 0; n == 0 && err == nil; i++ {
		if i == 100 {
			return nil, io.ErrNoProgress
		}
		n, err = r.Read(d.tmp[:1])
	}
	if err != nil && err != io.EOF {
		return nil, FormatError(err.Error())
	}
	if n != 0 || d.idatLength != 0 {
		return nil, FormatError("too much pixel data")
	}

	return img, nil
}

// decode decodes the IDAT data into an image.

decode decodes the IDAT data into an image .


func Decode(r io.Reader) (image.Image, error) {
	d := &decoder{
		r:   r,
		crc: crc32.NewIEEE(),
	}
	if err := d.checkHeader(); err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return nil, err
	}
	for d.stage != dsSeenIEND {
		if err := d.parseChunk(); err != nil {
			if err == io.EOF {
				err = io.ErrUnexpectedEOF
			}
			return nil, err
		}
	}
	return d.img, nil
}

func Decode ( r io . Reader ) ( image . Image , error ) { d := & decoder { r : r , crc : crc32 . NewIEEE ( ) , } if err := d . checkHeader ( ) ; err != nil { if err == io . EOF { err = io . ErrUnexpectedEOF } return nil , err } for d . stage != dsSeenIEND { if err := d . parseChunk ( ) ; err != nil { if err == io . EOF { err = io . ErrUnexpectedEOF } return nil , err } } return d . img , nil }

// Decode reads a PNG image from r and returns it as an image.Image.
// The type of Image returned depends on the PNG contents.

Decode reads a PNG image from r and returns it as an image . Image . The type of Image returned depends on the PNG contents .


func DecodeConfig(r io.Reader) (image.Config, error) {
	d := &decoder{
		r:   r,
		crc: crc32.NewIEEE(),
	}
	if err := d.checkHeader(); err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return image.Config{}, err
	}
	for {
		if err := d.parseChunk(); err != nil {
			if err == io.EOF {
				err = io.ErrUnexpectedEOF
			}
			return image.Config{}, err
		}
		paletted := cbPaletted(d.cb)
		if d.stage == dsSeenIHDR && !paletted {
			break
		}
		if d.stage == dsSeenPLTE && paletted {
			break
		}
	}
	var cm color.Model
	switch d.cb {
	case cbG1, cbG2, cbG4, cbG8:
		cm = color.GrayModel
	case cbGA8:
		cm = color.NRGBAModel
	case cbTC8:
		cm = color.RGBAModel
	case cbP1, cbP2, cbP4, cbP8:
		cm = d.palette
	case cbTCA8:
		cm = color.NRGBAModel
	case cbG16:
		cm = color.Gray16Model
	case cbGA16:
		cm = color.NRGBA64Model
	case cbTC16:
		cm = color.RGBA64Model
	case cbTCA16:
		cm = color.NRGBA64Model
	}
	return image.Config{
		ColorModel: cm,
		Width:      d.width,
		Height:     d.height,
	}, nil
}

func DecodeConfig ( r io . Reader ) ( image . Config , error ) { d := & decoder { r : r , crc : crc32 . NewIEEE ( ) , } if err := d . checkHeader ( ) ; err != nil { if err == io . EOF { err = io . ErrUnexpectedEOF } return image . Config { } , err } for { if err := d . parseChunk ( ) ; err != nil { if err == io . EOF { err = io . ErrUnexpectedEOF } return image . Config { } , err } paletted := cbPaletted ( d . cb ) if d . stage == dsSeenIHDR && ! paletted { break } if d . stage == dsSeenPLTE && paletted { break } } var cm color . Model switch d . cb { case cbG1 , cbG2 , cbG4 , cbG8 : cm = color . GrayModel case cbGA8 : cm = color . NRGBAModel case cbTC8 : cm = color . RGBAModel case cbP1 , cbP2 , cbP4 , cbP8 : cm = d . palette case cbTCA8 : cm = color . NRGBAModel case cbG16 : cm = color . Gray16Model case cbGA16 : cm = color . NRGBA64Model case cbTC16 : cm = color . RGBA64Model case cbTCA16 : cm = color . NRGBA64Model } return image . Config { ColorModel : cm , Width : d . width , Height : d . height , } , nil }

// DecodeConfig returns the color model and dimensions of a PNG image without
// decoding the entire image.

DecodeConfig returns the color model and dimensions of a PNG image without decoding the entire image .


func (c *ColorM) Add(other *ColorM) *ColorM {
	lhsb := colorMIdentityBody
	lhst := colorMIdentityTranslate
	rhsb := colorMIdentityBody
	rhst := colorMIdentityTranslate
	if other.isInited() {
		if other.body != nil {
			lhsb = other.body
		}
		if other.translate != nil {
			lhst = other.translate
		}
	}
	if c.isInited() {
		if c.body != nil {
			rhsb = c.body
		}
		if c.translate != nil {
			rhst = c.translate
		}
	}

	newC := &ColorM{
		body:      make([]float32, 16),
		translate: make([]float32, 4),
	}
	for i := range lhsb {
		newC.body[i] = lhsb[i] + rhsb[i]
	}
	for i := range lhst {
		newC.translate[i] = lhst[i] + rhst[i]
	}

	return newC
}

func ( c * ColorM ) Add ( other * ColorM ) * ColorM { lhsb := colorMIdentityBody lhst := colorMIdentityTranslate rhsb := colorMIdentityBody rhst := colorMIdentityTranslate if other . isInited ( ) { if other . body != nil { lhsb = other . body } if other . translate != nil { lhst = other . translate } } if c . isInited ( ) { if c . body != nil { rhsb = c . body } if c . translate != nil { rhst = c . translate } } newC := & ColorM { body : make ( [ ] float32 , 16 ) , translate : make ( [ ] float32 , 4 ) , } for i := range lhsb { newC . body [ i ] = lhsb [ i ] + rhsb [ i ] } for i := range lhst { newC . translate [ i ] = lhst [ i ] + rhst [ i ] } return newC }


func (c *gamepadConfig) IsButtonPressed(b virtualGamepadButton) bool {
	if !c.gamepadIDInitialized {
		panic("not reached")
	}

	c.initializeIfNeeded()

	bb, ok := c.buttons[b]
	if ok {
		return ebiten.IsGamepadButtonPressed(c.gamepadID, bb)
	}

	a, ok := c.axes[b]
	if ok {
		v := ebiten.GamepadAxis(c.gamepadID, a.id)
		if a.positive {
			return axisThreshold <= v && v <= 1.0
		} else {
			return -1.0 <= v && v <= -axisThreshold
		}
	}
	return false
}

func ( c * gamepadConfig ) IsButtonPressed ( b virtualGamepadButton ) bool { if ! c . gamepadIDInitialized { panic ( " " ) } c . initializeIfNeeded ( ) bb , ok := c . buttons [ b ] if ok { return ebiten . IsGamepadButtonPressed ( c . gamepadID , bb ) } a , ok := c . axes [ b ] if ok { v := ebiten . GamepadAxis ( c . gamepadID , a . id ) if a . positive { return axisThreshold <= v && v <= 1.0 } else { return - 1.0 <= v && v <= - axisThreshold } } return false }

// IsButtonPressed returns a boolean value indicating whether
// the given virtual button b is pressed.

IsButtonPressed returns a boolean value indicating whether the given virtual button b is pressed .


func (c *gamepadConfig) ButtonName(b virtualGamepadButton) string {
	if !c.gamepadIDInitialized {
		panic("not reached")
	}

	c.initializeIfNeeded()

	bb, ok := c.buttons[b]
	if ok {
		return fmt.Sprintf("Button %d", bb)
	}

	a, ok := c.axes[b]
	if ok {
		if a.positive {
			return fmt.Sprintf("Axis %d+", a.id)
		} else {
			return fmt.Sprintf("Axis %d-", a.id)
		}
	}

	return ""
}

func ( c * gamepadConfig ) ButtonName ( b virtualGamepadButton ) string { if ! c . gamepadIDInitialized { panic ( " " ) } c . initializeIfNeeded ( ) bb , ok := c . buttons [ b ] if ok { return fmt . Sprintf ( " " , bb ) } a , ok := c . axes [ b ] if ok { if a . positive { return fmt . Sprintf ( " " , a . id ) } else { return fmt . Sprintf ( " " , a . id ) } } return " " }

// Name returns the pysical button's name for the given virtual button.

Name returns the pysical button s name for the given virtual button .


func AppendHookOnBeforeUpdate(f func() error) {
	m.Lock()
	onBeforeUpdateHooks = append(onBeforeUpdateHooks, f)
	m.Unlock()
}

func AppendHookOnBeforeUpdate ( f func ( ) error ) { m . Lock ( ) onBeforeUpdateHooks = append ( onBeforeUpdateHooks , f ) m . Unlock ( ) }

// AppendHookOnBeforeUpdate appends a hook function that is run before the main update function
// every frame.

AppendHookOnBeforeUpdate appends a hook function that is run before the main update function every frame .


func DebugPrint(image *ebiten.Image, str string) error {
	DebugPrintAt(image, str, 0, 0)
	return nil
}

func DebugPrint ( image * ebiten . Image , str string ) error { DebugPrintAt ( image , str , 0 , 0 ) return nil }

// DebugPrint draws the string str on the image on left top corner.
//
// The available runes are in U+0000 to U+00FF, which is C0 Controls and Basic Latin and C1 Controls and Latin-1 Supplement.
//
// DebugPrint always returns nil as of 1.5.0-alpha.

DebugPrint draws the string str on the image on left top corner . The available runes are in U + 0000 to U + 00FF which is C0 Controls and Basic Latin and C1 Controls and Latin - 1 Supplement . DebugPrint always returns nil as of 1 . 5 . 0 - alpha .


func (i *Input) GamepadIDButtonPressed() int {
	for _, id := range ebiten.GamepadIDs() {
		for b := ebiten.GamepadButton(0); b <= ebiten.GamepadButtonMax; b++ {
			if ebiten.IsGamepadButtonPressed(id, b) {
				return id
			}
		}
	}
	return -1
}

func ( i * Input ) GamepadIDButtonPressed ( ) int { for _ , id := range ebiten . GamepadIDs ( ) { for b := ebiten . GamepadButton ( 0 ) ; b <= ebiten . GamepadButtonMax ; b ++ { if ebiten . IsGamepadButtonPressed ( id , b ) { return id } } } return - 1 }

// GamepadIDButtonPressed returns a gamepad ID where at least one button is pressed.
// If no button is pressed, GamepadIDButtonPressed returns -1.

GamepadIDButtonPressed returns a gamepad ID where at least one button is pressed . If no button is pressed GamepadIDButtonPressed returns - 1 .


func (s *Stream) Seek(offset int64, whence int) (int64, error) {
	return s.decoded.Seek(offset, whence)
}

func ( s * Stream ) Seek ( offset int64 , whence int ) ( int64 , error ) { return s . decoded . Seek ( offset , whence ) }

// Seek is implementation of io.Seeker's Seek.
//
// Note that Seek can take long since decoding is a relatively heavy task.

Seek is implementation of io . Seeker s Seek . Note that Seek can take long since decoding is a relatively heavy task .


func decode(in audio.ReadSeekCloser) (*decoded, int, int, error) {
	r, err := newDecoder(in)
	if err != nil {
		return nil, 0, 0, err
	}
	d := &decoded{
		// TODO: r.Length() returns 0 when the format is unknown.
		// Should we check that?
		totalBytes: int(r.Length()) * r.Channels() * 2, // 2 means 16bit per sample.
		posInBytes: 0,
		source:     in,
		decoder:    r,
	}
	runtime.SetFinalizer(d, (*decoded).Close)
	if _, err := d.Read(make([]byte, 65536)); err != nil && err != io.EOF {
		return nil, 0, 0, err
	}
	if _, err := d.Seek(0, io.SeekStart); err != nil {
		return nil, 0, 0, err
	}
	return d, r.Channels(), r.SampleRate(), nil
}

// decode accepts an ogg stream and returns a decorded stream.

decode accepts an ogg stream and returns a decorded stream .


func (f *Field) MovePieceToLeft(piece *Piece, x, y int, angle Angle) int {
	if piece.collides(f, x-1, y, angle) {
		return x
	}
	return x - 1
}

func ( f * Field ) MovePieceToLeft ( piece * Piece , x , y int , angle Angle ) int { if piece . collides ( f , x - 1 , y , angle ) { return x } return x - 1 }

// MovePieceToLeft tries to move the piece to the left
// and returns the piece's next x position.

MovePieceToLeft tries to move the piece to the left and returns the piece s next x position .


func (f *Field) RotatePieceRight(piece *Piece, x, y int, angle Angle) Angle {
	if piece.collides(f, x, y, angle.RotateRight()) {
		return angle
	}
	return angle.RotateRight()
}

func ( f * Field ) RotatePieceRight ( piece * Piece , x , y int , angle Angle ) Angle { if piece . collides ( f , x , y , angle . RotateRight ( ) ) { return angle } return angle . RotateRight ( ) }

// RotatePieceRight tries to rotate the piece to the right
// and returns the piece's next angle.

RotatePieceRight tries to rotate the piece to the right and returns the piece s next angle .


func (f *Field) RotatePieceLeft(piece *Piece, x, y int, angle Angle) Angle {
	if piece.collides(f, x, y, angle.RotateLeft()) {
		return angle
	}
	return angle.RotateLeft()
}

func ( f * Field ) RotatePieceLeft ( piece * Piece , x , y int , angle Angle ) Angle { if piece . collides ( f , x , y , angle . RotateLeft ( ) ) { return angle } return angle . RotateLeft ( ) }

// RotatePieceLeft tries to rotate the piece to the left
// and returns the piece's next angle.

RotatePieceLeft tries to rotate the piece to the left and returns the piece s next angle .


func (f *Field) flushable() bool {
	for j := fieldBlockNumY - 1; 0 <= j; j-- {
		if f.flushableLine(j) {
			return true
		}
	}
	return false
}

func ( f * Field ) flushable ( ) bool { for j := fieldBlockNumY - 1 ; 0 <= j ; j -- { if f . flushableLine ( j ) { return true } } return false }

// flushable returns a boolean value indicating whether
// there is a flushable line in the field.

flushable returns a boolean value indicating whether there is a flushable line in the field .


func (f *Field) flushableLine(j int) bool {
	for i := 0; i < fieldBlockNumX; i++ {
		if f.blocks[i][j] == BlockTypeNone {
			return false
		}
	}
	return true
}

func ( f * Field ) flushableLine ( j int ) bool { for i := 0 ; i < fieldBlockNumX ; i ++ { if f . blocks [ i ] [ j ] == BlockTypeNone { return false } } return true }

// flushableLine returns a boolean value indicating whether
// the line j is flushabled or not.

flushableLine returns a boolean value indicating whether the line j is flushabled or not .


func (f *Field) flushLine(j int) bool {
	for i := 0; i < fieldBlockNumX; i++ {
		if f.blocks[i][j] == BlockTypeNone {
			return false
		}
	}
	for j2 := j; 1 <= j2; j2-- {
		for i := 0; i < fieldBlockNumX; i++ {
			f.blocks[i][j2] = f.blocks[i][j2-1]
		}
	}
	for i := 0; i < fieldBlockNumX; i++ {
		f.blocks[i][0] = BlockTypeNone
	}
	return true
}

func ( f * Field ) flushLine ( j int ) bool { for i := 0 ; i < fieldBlockNumX ; i ++ { if f . blocks [ i ] [ j ] == BlockTypeNone { return false } } for j2 := j ; 1 <= j2 ; j2 -- { for i := 0 ; i < fieldBlockNumX ; i ++ { f . blocks [ i ] [ j2 ] = f . blocks [ i ] [ j2 - 1 ] } } for i := 0 ; i < fieldBlockNumX ; i ++ { f . blocks [ i ] [ 0 ] = BlockTypeNone } return true }

// flushLine flushes the line j if possible, and if the line is flushed,
// the other lines above the line go down.
//
// flushLine returns a boolean value indicating whether
// the line is actually flushed.

flushLine flushes the line j if possible and if the line is flushed the other lines above the line go down . flushLine returns a boolean value indicating whether the line is actually flushed .


func intersection(l1, l2 line) (float64, float64, bool) {
	// https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line
	denom := (l1.X1-l1.X2)*(l2.Y1-l2.Y2) - (l1.Y1-l1.Y2)*(l2.X1-l2.X2)
	tNum := (l1.X1-l2.X1)*(l2.Y1-l2.Y2) - (l1.Y1-l2.Y1)*(l2.X1-l2.X2)
	uNum := -((l1.X1-l1.X2)*(l1.Y1-l2.Y1) - (l1.Y1-l1.Y2)*(l1.X1-l2.X1))

	if denom == 0 {
		return 0, 0, false
	}

	t := tNum / denom
	if t > 1 || t < 0 {
		return 0, 0, false
	}

	u := uNum / denom
	if u > 1 || u < 0 {
		return 0, 0, false
	}

	x := l1.X1 + t*(l1.X2-l1.X1)
	y := l1.Y1 + t*(l1.Y2-l1.Y1)
	return x, y, true
}

// intersection calculates the intersection of given two lines.

intersection calculates the intersection of given two lines .


func rayCasting(cx, cy float64, objects []object) []line {
	const rayLength = 1000 // something large enough to reach all objects

	var rays []line
	for _, obj := range objects {
		// Cast two rays per point
		for _, p := range obj.points() {
			l := line{cx, cy, p[0], p[1]}
			angle := l.angle()

			for _, offset := range []float64{-0.005, 0.005} {
				points := [][2]float64{}
				ray := newRay(cx, cy, rayLength, angle+offset)

				// Unpack all objects
				for _, o := range objects {
					for _, wall := range o.walls {
						if px, py, ok := intersection(ray, wall); ok {
							points = append(points, [2]float64{px, py})
						}
					}
				}

				// Find the point closest to start of ray
				min := math.Inf(1)
				minI := -1
				for i, p := range points {
					d2 := (cx-p[0])*(cx-p[0]) + (cy-p[1])*(cy-p[1])
					if d2 < min {
						min = d2
						minI = i
					}
				}
				rays = append(rays, line{cx, cy, points[minI][0], points[minI][1]})
			}
		}
	}

	// Sort rays based on angle, otherwise light triangles will not come out right
	sort.Slice(rays, func(i int, j int) bool {
		return rays[i].angle() < rays[j].angle()
	})
	return rays
}

// rayCasting returns a slice of line originating from point cx, cy and intersecting with objects

rayCasting returns a slice of line originating from point cx cy and intersecting with objects


func Str(str string) *uint8 {
	if !strings.HasSuffix(str, "\x00") {
		panic("str argument missing null terminator: " + str)
	}
	header := (*reflect.StringHeader)(unsafe.Pointer(&str))
	return (*uint8)(unsafe.Pointer(header.Data))
}

func Str ( str string ) * uint8 { if ! strings . HasSuffix ( str , " \x00 " ) { panic ( " " + str ) } header := ( * reflect . StringHeader ) ( unsafe . Pointer ( & str ) ) return ( * uint8 ) ( unsafe . Pointer ( header . Data ) ) }

// Str takes a null-terminated Go string and returns its GL-compatible address.
// This function reaches into Go string storage in an unsafe way so the caller
// must ensure the string is not garbage collected.

Str takes a null - terminated Go string and returns its GL - compatible address . This function reaches into Go string storage in an unsafe way so the caller must ensure the string is not garbage collected .


func (s *Stream) Close() error {
	runtime.SetFinalizer(s, nil)
	return s.inner.Close()
}

func ( s * Stream ) Close ( ) error { runtime . SetFinalizer ( s , nil ) return s . inner . Close ( ) }

// Read is implementation of io.Closer's Close.

Read is implementation of io . Closer s Close .


func NewWorld(width, height int, maxInitLiveCells int) *World {
	w := &World{
		area:   make([]bool, width*height),
		width:  width,
		height: height,
	}
	w.init(maxInitLiveCells)
	return w
}

func NewWorld ( width , height int , maxInitLiveCells int ) * World { w := & World { area : make ( [ ] bool , width * height ) , width : width , height : height , } w . init ( maxInitLiveCells ) return w }


func (w *World) init(maxLiveCells int) {
	for i := 0; i < maxLiveCells; i++ {
		x := rand.Intn(w.width)
		y := rand.Intn(w.height)
		w.area[y*w.width+x] = true
	}
}

func ( w * World ) init ( maxLiveCells int ) { for i := 0 ; i < maxLiveCells ; i ++ { x := rand . Intn ( w . width ) y := rand . Intn ( w . height ) w . area [ y * w . width + x ] = true } }

// init inits world with a random state.


func (w *World) Update() {
	width := w.width
	height := w.height
	next := make([]bool, width*height)
	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			pop := neighbourCount(w.area, width, height, x, y)
			switch {
			case pop < 2:
				// rule 1. Any live cell with fewer than two live neighbours
				// dies, as if caused by under-population.
				next[y*width+x] = false

			case (pop == 2 || pop == 3) && w.area[y*width+x]:
				// rule 2. Any live cell with two or three live neighbours
				// lives on to the next generation.
				next[y*width+x] = true

			case pop > 3:
				// rule 3. Any live cell with more than three live neighbours
				// dies, as if by over-population.
				next[y*width+x] = false

			case pop == 3:
				// rule 4. Any dead cell with exactly three live neighbours
				// becomes a live cell, as if by reproduction.
				next[y*width+x] = true
			}
		}
	}
	w.area = next
}


func (w *World) Draw(pix []byte) {
	for i, v := range w.area {
		if v {
			pix[4*i] = 0xff
			pix[4*i+1] = 0xff
			pix[4*i+2] = 0xff
			pix[4*i+3] = 0xff
		} else {
			pix[4*i] = 0
			pix[4*i+1] = 0
			pix[4*i+2] = 0
			pix[4*i+3] = 0
		}
	}
}

func ( w * World ) Draw ( pix [ ] byte ) { for i , v := range w . area { if v { pix [ 4 * i ] = 0xff pix [ 4 * i + 1 ] = 0xff pix [ 4 * i + 2 ] = 0xff pix [ 4 * i + 3 ] = 0xff } else { pix [ 4 * i ] = 0 pix [ 4 * i + 1 ] = 0 pix [ 4 * i + 2 ] = 0 pix [ 4 * i + 3 ] = 0 } } }


func DrawLine(dst *ebiten.Image, x1, y1, x2, y2 float64, clr color.Color) {
	ew, eh := emptyImage.Size()
	length := math.Hypot(x2-x1, y2-y1)

	op := &ebiten.DrawImageOptions{}
	op.GeoM.Scale(length/float64(ew), 1/float64(eh))
	op.GeoM.Rotate(math.Atan2(y2-y1, x2-x1))
	op.GeoM.Translate(x1, y1)
	op.ColorM.Scale(colorScale(clr))
	// Filter must be 'nearest' filter (default).
	// Linear filtering would make edges blurred.
	_ = dst.DrawImage(emptyImage, op)
}

// DrawLine draws a line segment on the given destination dst.
//
// DrawLine is intended to be used mainly for debugging or prototyping purpose.

DrawLine draws a line segment on the given destination dst . DrawLine is intended to be used mainly for debugging or prototyping purpose .


func DrawRect(dst *ebiten.Image, x, y, width, height float64, clr color.Color) {
	ew, eh := emptyImage.Size()

	op := &ebiten.DrawImageOptions{}
	op.GeoM.Scale(width/float64(ew), height/float64(eh))
	op.GeoM.Translate(x, y)
	op.ColorM.Scale(colorScale(clr))
	// Filter must be 'nearest' filter (default).
	// Linear filtering would make edges blurred.
	_ = dst.DrawImage(emptyImage, op)
}

// DrawRect draws a rectangle on the given destination dst.
//
// DrawRect is intended to be used mainly for debugging or prototyping purpose.

DrawRect draws a rectangle on the given destination dst . DrawRect is intended to be used mainly for debugging or prototyping purpose .


func NewGame() (*Game, error) {
	g := &Game{
		input: NewInput(),
	}
	var err error
	g.board, err = NewBoard(boardSize)
	if err != nil {
		return nil, err
	}
	return g, nil
}

func NewGame ( ) ( * Game , error ) { g := & Game { input : NewInput ( ) , } var err error g . board , err = NewBoard ( boardSize ) if err != nil { return nil , err } return g , nil }


func (g *Game) Update() error {
	g.input.Update()
	if err := g.board.Update(g.input); err != nil {
		return err
	}
	return nil
}

func ( g * Game ) Update ( ) error { g . input . Update ( ) if err := g . board . Update ( g . input ) ; err != nil { return err } return nil }

// Update updates the current game state.


func (g *Game) Draw(screen *ebiten.Image) {
	if g.boardImage == nil {
		w, h := g.board.Size()
		g.boardImage, _ = ebiten.NewImage(w, h, ebiten.FilterDefault)
	}
	screen.Fill(backgroundColor)
	g.board.Draw(g.boardImage)
	op := &ebiten.DrawImageOptions{}
	sw, sh := screen.Size()
	bw, bh := g.boardImage.Size()
	x := (sw - bw) / 2
	y := (sh - bh) / 2
	op.GeoM.Translate(float64(x), float64(y))
	screen.DrawImage(g.boardImage, op)
}

func ( g * Game ) Draw ( screen * ebiten . Image ) { if g . boardImage == nil { w , h := g . board . Size ( ) g . boardImage , _ = ebiten . NewImage ( w , h , ebiten . FilterDefault ) } screen . Fill ( backgroundColor ) g . board . Draw ( g . boardImage ) op := & ebiten . DrawImageOptions { } sw , sh := screen . Size ( ) bw , bh := g . boardImage . Size ( ) x := ( sw - bw ) / 2 y := ( sh - bh ) / 2 op . GeoM . Translate ( float64 ( x ) , float64 ( y ) ) screen . DrawImage ( g . boardImage , op ) }

// Draw draws the current game to the given screen.

Draw draws the current game to the given screen .


func IsKeyJustReleased(key ebiten.Key) bool {
	theInputState.m.RLock()
	r := theInputState.keyDurations[key] == 0 && theInputState.prevKeyDurations[key] > 0
	theInputState.m.RUnlock()
	return r
}

func IsKeyJustReleased ( key ebiten . Key ) bool { theInputState . m . RLock ( ) r := theInputState . keyDurations [ key ] == 0 && theInputState . prevKeyDurations [ key ] > 0 theInputState . m . RUnlock ( ) return r }

// IsKeyJustReleased returns a boolean value indicating
// whether the given key is released just in the current frame.
//
// IsKeyJustReleased is concurrent safe.

IsKeyJustReleased returns a boolean value indicating whether the given key is released just in the current frame . IsKeyJustReleased is concurrent safe .


func KeyPressDuration(key ebiten.Key) int {
	theInputState.m.RLock()
	s := theInputState.keyDurations[key]
	theInputState.m.RUnlock()
	return s
}

func KeyPressDuration ( key ebiten . Key ) int { theInputState . m . RLock ( ) s := theInputState . keyDurations [ key ] theInputState . m . RUnlock ( ) return s }

// KeyPressDuration returns how long the key is pressed in frames.
//
// KeyPressDuration is concurrent safe.

KeyPressDuration returns how long the key is pressed in frames . KeyPressDuration is concurrent safe .


func IsMouseButtonJustReleased(button ebiten.MouseButton) bool {
	theInputState.m.RLock()
	r := theInputState.mouseButtonDurations[button] == 0 &&
		theInputState.prevMouseButtonDurations[button] > 0
	theInputState.m.RUnlock()
	return r
}

func IsMouseButtonJustReleased ( button ebiten . MouseButton ) bool { theInputState . m . RLock ( ) r := theInputState . mouseButtonDurations [ button ] == 0 && theInputState . prevMouseButtonDurations [ button ] > 0 theInputState . m . RUnlock ( ) return r }

// IsMouseButtonJustReleased returns a boolean value indicating
// whether the given mouse button is released just in the current frame.
//
// IsMouseButtonJustReleased is concurrent safe.

IsMouseButtonJustReleased returns a boolean value indicating whether the given mouse button is released just in the current frame . IsMouseButtonJustReleased is concurrent safe .


func MouseButtonPressDuration(button ebiten.MouseButton) int {
	theInputState.m.RLock()
	s := theInputState.mouseButtonDurations[button]
	theInputState.m.RUnlock()
	return s
}

func MouseButtonPressDuration ( button ebiten . MouseButton ) int { theInputState . m . RLock ( ) s := theInputState . mouseButtonDurations [ button ] theInputState . m . RUnlock ( ) return s }

// MouseButtonPressDuration returns how long the mouse button is pressed in frames.
//
// MouseButtonPressDuration is concurrent safe.

MouseButtonPressDuration returns how long the mouse button is pressed in frames . MouseButtonPressDuration is concurrent safe .


func JustConnectedGamepadIDs() []int {
	var ids []int
	theInputState.m.RLock()
	for id := range theInputState.gamepadIDs {
		if _, ok := theInputState.prevGamepadIDs[id]; !ok {
			ids = append(ids, id)
		}
	}
	theInputState.m.RUnlock()
	sort.Ints(ids)
	return ids
}

func JustConnectedGamepadIDs ( ) [ ] int { var ids [ ] int theInputState . m . RLock ( ) for id := range theInputState . gamepadIDs { if _ , ok := theInputState . prevGamepadIDs [ id ] ; ! ok { ids = append ( ids , id ) } } theInputState . m . RUnlock ( ) sort . Ints ( ids ) return ids }

// JustConnectedGamepadIDs returns gamepad IDs that are connected just in the current frame.
//
// JustConnectedGamepadIDs might return nil when there is no connected gamepad.
//
// JustConnectedGamepadIDs is concurrent safe.

JustConnectedGamepadIDs returns gamepad IDs that are connected just in the current frame . JustConnectedGamepadIDs might return nil when there is no connected gamepad . JustConnectedGamepadIDs is concurrent safe .


func IsGamepadJustDisconnected(id int) bool {
	theInputState.m.RLock()
	_, prev := theInputState.prevGamepadIDs[id]
	_, current := theInputState.gamepadIDs[id]
	theInputState.m.RUnlock()
	return prev && !current
}

func IsGamepadJustDisconnected ( id int ) bool { theInputState . m . RLock ( ) _ , prev := theInputState . prevGamepadIDs [ id ] _ , current := theInputState . gamepadIDs [ id ] theInputState . m . RUnlock ( ) return prev && ! current }

// IsGamepadJustDisconnected returns a boolean value indicating
// whether the gamepad of the given id is released just in the current frame.
//
// IsGamepadJustDisconnected is concurrent safe.

IsGamepadJustDisconnected returns a boolean value indicating whether the gamepad of the given id is released just in the current frame . IsGamepadJustDisconnected is concurrent safe .


func IsGamepadButtonJustPressed(id int, button ebiten.GamepadButton) bool {
	return GamepadButtonPressDuration(id, button) == 1
}

func IsGamepadButtonJustPressed ( id int , button ebiten . GamepadButton ) bool { return GamepadButtonPressDuration ( id , button ) == 1 }

// IsGamepadButtonJustPressed returns a boolean value indicating
// whether the given gamepad button of the gamepad id is pressed just in the current frame.
//
// IsGamepadButtonJustPressed is concurrent safe.

IsGamepadButtonJustPressed returns a boolean value indicating whether the given gamepad button of the gamepad id is pressed just in the current frame . IsGamepadButtonJustPressed is concurrent safe .


func IsGamepadButtonJustReleased(id int, button ebiten.GamepadButton) bool {
	theInputState.m.RLock()
	prev := 0
	if _, ok := theInputState.prevGamepadButtonDurations[id]; ok {
		prev = theInputState.prevGamepadButtonDurations[id][button]
	}
	current := 0
	if _, ok := theInputState.gamepadButtonDurations[id]; ok {
		current = theInputState.gamepadButtonDurations[id][button]
	}
	theInputState.m.RUnlock()
	return current == 0 && prev > 0
}

func IsGamepadButtonJustReleased ( id int , button ebiten . GamepadButton ) bool { theInputState . m . RLock ( ) prev := 0 if _ , ok := theInputState . prevGamepadButtonDurations [ id ] ; ok { prev = theInputState . prevGamepadButtonDurations [ id ] [ button ] } current := 0 if _ , ok := theInputState . gamepadButtonDurations [ id ] ; ok { current = theInputState . gamepadButtonDurations [ id ] [ button ] } theInputState . m . RUnlock ( ) return current == 0 && prev > 0 }

// IsGamepadButtonJustReleased returns a boolean value indicating
// whether the given gamepad button of the gamepad id is released just in the current frame.
//
// IsGamepadButtonJustReleased is concurrent safe.

IsGamepadButtonJustReleased returns a boolean value indicating whether the given gamepad button of the gamepad id is released just in the current frame . IsGamepadButtonJustReleased is concurrent safe .


func GamepadButtonPressDuration(id int, button ebiten.GamepadButton) int {
	theInputState.m.RLock()
	s := 0
	if _, ok := theInputState.gamepadButtonDurations[id]; ok {
		s = theInputState.gamepadButtonDurations[id][button]
	}
	theInputState.m.RUnlock()
	return s
}

func GamepadButtonPressDuration ( id int , button ebiten . GamepadButton ) int { theInputState . m . RLock ( ) s := 0 if _ , ok := theInputState . gamepadButtonDurations [ id ] ; ok { s = theInputState . gamepadButtonDurations [ id ] [ button ] } theInputState . m . RUnlock ( ) return s }

// GamepadButtonPressDuration returns how long the gamepad button of the gamepad id is pressed in frames.
//
// GamepadButtonPressDuration is concurrent safe.

GamepadButtonPressDuration returns how long the gamepad button of the gamepad id is pressed in frames . GamepadButtonPressDuration is concurrent safe .


func JustPressedTouchIDs() []int {
	var ids []int
	theInputState.m.RLock()
	for id, s := range theInputState.touchDurations {
		if s == 1 {
			ids = append(ids, id)
		}
	}
	theInputState.m.RUnlock()
	sort.Ints(ids)
	return ids
}

func JustPressedTouchIDs ( ) [ ] int { var ids [ ] int theInputState . m . RLock ( ) for id , s := range theInputState . touchDurations { if s == 1 { ids = append ( ids , id ) } } theInputState . m . RUnlock ( ) sort . Ints ( ids ) return ids }

// JustPressedTouchIDs returns touch IDs that are created just in the current frame.
//
// JustPressedTouchIDs might return nil when there is not touch.
//
// JustPressedTouchIDs is concurrent safe.

JustPressedTouchIDs returns touch IDs that are created just in the current frame . JustPressedTouchIDs might return nil when there is not touch . JustPressedTouchIDs is concurrent safe .


func IsTouchJustReleased(id int) bool {
	theInputState.m.RLock()
	r := theInputState.touchDurations[id] == 0 && theInputState.prevTouchDurations[id] > 0
	theInputState.m.RUnlock()
	return r
}

func IsTouchJustReleased ( id int ) bool { theInputState . m . RLock ( ) r := theInputState . touchDurations [ id ] == 0 && theInputState . prevTouchDurations [ id ] > 0 theInputState . m . RUnlock ( ) return r }

// IsTouchJustReleased returns a boolean value indicating
// whether the given touch is released just in the current frame.
//
// IsTouchJustReleased is concurrent safe.

IsTouchJustReleased returns a boolean value indicating whether the given touch is released just in the current frame . IsTouchJustReleased is concurrent safe .


func TouchPressDuration(id int) int {
	theInputState.m.RLock()
	s := theInputState.touchDurations[id]
	theInputState.m.RUnlock()
	return s
}

func TouchPressDuration ( id int ) int { theInputState . m . RLock ( ) s := theInputState . touchDurations [ id ] theInputState . m . RUnlock ( ) return s }

// TouchPressDuration returns how long the touch remains in frames.
//
// TouchPressDuration is concurrent safe.

TouchPressDuration returns how long the touch remains in frames . TouchPressDuration is concurrent safe .


func (i *Image) viewportSize() (int, int) {
	if i.screen {
		return i.width, i.height
	}
	return graphics.InternalImageSize(i.width), graphics.InternalImageSize(i.height)
}

func ( i * Image ) viewportSize ( ) ( int , int ) { if i . screen { return i . width , i . height } return graphics . InternalImageSize ( i . width ) , graphics . InternalImageSize ( i . height ) }

// viewportSize must be called from the main thread.

viewportSize must be called from the main thread .


func Loop(ch <-chan error) error {
	atomic.StoreInt32(&started, 1)
	for {
		select {
		case f := <-funcs:
			f()
		case err := <-ch:
			// ch returns a value not only when an error occur but also it is closed.
			return err
		}
	}
}

// Loop starts the main-thread loop.
//
// Loop must be called on the main thread.

Loop starts the main - thread loop . Loop must be called on the main thread .


func Run(f func() error) error {
	if atomic.LoadInt32(&started) == 0 {
		// TODO: This can reach from other goroutine before Loop is called (#809).
		// panic("mainthread: the mainthread loop is not started yet")
	}

	ch := make(chan struct{})
	var err error
	funcs <- func() {
		err = f()
		close(ch)
	}
	<-ch
	return err
}

// Run calls f on the main thread.
//
// Do not call this from the main thread. This would block forever.

Run calls f on the main thread . Do not call this from the main thread . This would block forever .


func InternalImageSize(x int) int {
	if x <= 0 {
		panic("graphics: x must be positive")
	}
	if x < minInternalImageSize {
		return minInternalImageSize
	}
	r := 1
	for r < x {
		r <<= 1
	}
	return r
}

func InternalImageSize ( x int ) int { if x <= 0 { panic ( " " ) } if x < minInternalImageSize { return minInternalImageSize } r := 1 for r < x { r <<= 1 } return r }

// InternalImageSize returns a nearest appropriate size as an internal image.

InternalImageSize returns a nearest appropriate size as an internal image .


func square(out []int16, volume float64, freq float64, sequence float64) {
	if freq == 0 {
		for i := 0; i < len(out); i++ {
			out[i] = 0
		}
		return
	}
	length := int(float64(sampleRate) / freq)
	if length == 0 {
		panic("invalid freq")
	}
	for i := 0; i < len(out); i++ {
		a := int16(volume * math.MaxInt16)
		if i%length < int(float64(length)*sequence) {
			a = -a
		}
		out[i] = a
	}
}

func square ( out [ ] int16 , volume float64 , freq float64 , sequence float64 ) { if freq == 0 { for i := 0 ; i < len ( out ) ; i ++ { out [ i ] = 0 } return } length := int ( float64 ( sampleRate ) / freq ) if length == 0 { panic ( " " ) } for i := 0 ; i < len ( out ) ; i ++ { a := int16 ( volume * math . MaxInt16 ) if i % length < int ( float64 ( length ) * sequence ) { a = - a } out [ i ] = a } }

// square fills out with square wave values with the specified volume, frequency and sequence.

square fills out with square wave values with the specified volume frequency and sequence .


func playNote(scoreIndex int) rune {
	note := score[scoreIndex]

	// If the note is 'rest', play nothing.
	if note == 'R' {
		return rune(note)
	}

	freqs := []float64{freqC, freqD, freqE, freqF, freqG, freqA * 2, freqB * 2}
	freq := 0.0
	switch {
	case 'A' <= note && note <= 'B':
		freq = freqs[int(note)+len(freqs)-int('C')]
	case 'C' <= note && note <= 'G':
		freq = freqs[note-'C']
	default:
		panic("note out of range")
	}

	const vol = 1.0 / 16.0
	size := (ebiten.MaxTPS()/2 - 2) * sampleRate / ebiten.MaxTPS()
	l := make([]int16, size)
	r := make([]int16, size)
	square(l, vol, freq, 0.25)
	square(r, vol, freq, 0.25)

	p, _ := audio.NewPlayerFromBytes(audioContext, toBytes(l, r))
	p.Play()

	return rune(note)
}

func
playNote
(
scoreIndex
int
)
rune
{
note
:=
score
[
scoreIndex
]
// If the note is 'rest', play nothing.
if
note
==
'R'
{
return
rune
(
note
)
}
freqs
:=
[
]
float64
{
freqC
,
freqD
,
freqE
,
freqF
,
freqG
,
freqA
*
2
,
freqB
*
2
}
freq
:=
0.0
switch
{
case
'A'
<=
note
&&
note
<=
'B'
:
freq
=
freqs
[
int
(
note
)
+
len
(
freqs
)
int
(
'C'
)
]
case
'C'
<=
note
&&
note
<=
'G'
:
freq
=
freqs
[
note
'C'
]
default
:
panic
(
"
"
)
}
const
vol
=
1.0
/
16.0
size
:=
(
ebiten
.
MaxTPS
(
)
/
2
2
)
*
sampleRate
/
ebiten
.
MaxTPS
(
)
l
:=
make
(
[
]
int16
,
size
)
r
:=
make
(
[
]
int16
,
size
)
square
(
l
,
vol
,
freq
,
0.25
)
square
(
r
,
vol
,
freq
,
0.25
)
p
,
_
:=
audio
.
NewPlayerFromBytes
(
audioContext
,
toBytes
(
l
,
r
)
)
p
.
Play
(
)
return
rune
(
note
)
}

// playNote plays the note at scoreIndex of the score.

playNote plays the note at scoreIndex of the score .


func pianoAt(i int, freq float64) float64 {
	// Create piano-like waves with multiple sin waves.
	amp := []float64{1.0, 0.8, 0.6, 0.4, 0.2}
	x := []float64{4.0, 2.0, 1.0, 0.5, 0.25}
	v := 0.0
	for j := 0; j < len(amp); j++ {
		// Decay
		a := amp[j] * math.Exp(-5*float64(i)*freq/baseFreq/(x[j]*sampleRate))
		v += a * math.Sin(2.0*math.Pi*float64(i)*freq*float64(j+1)/sampleRate)
	}
	return v / 5.0
}

// pianoAt returns an i-th sample of piano with the given frequency.

pianoAt returns an i - th sample of piano with the given frequency .


func playNote(freq float64) {
	f := int(freq)
	p, _ := audio.NewPlayerFromBytes(audioContext, pianoNoteSamples[f])
	p.Play()
}

func playNote ( freq float64 ) { f := int ( freq ) p , _ := audio . NewPlayerFromBytes ( audioContext , pianoNoteSamples [ f ] ) p . Play ( ) }

// playNote plays piano sound with the given frequency.

playNote plays piano sound with the given frequency .


func (p *Path) Draw(target *ebiten.Image, op *DrawPathOptions) {
	if op == nil {
		return
	}

	// TODO: Implement filling
	if op.StrokeColor != nil {
		vs, is := p.strokeVertices(op.LineWidth, op.StrokeColor)
		op := &ebiten.DrawTrianglesOptions{}
		op.Address = ebiten.AddressRepeat
		target.DrawTriangles(vs, is, emptyImage, op)
	}
}

func
(
p
*
Path
)
Draw
(
target
*
ebiten
.
Image
,
op
*
DrawPathOptions
)
{
if
op
==
{
return
}
// TODO: Implement filling
if
op
.
StrokeColor
!=
{
vs
,
is
:=
p
.
strokeVertices
(
op
.
LineWidth
,
op
.
StrokeColor
)
op
:=
&
ebiten
.
DrawTrianglesOptions
{
}
op
.
Address
=
ebiten
.
AddressRepeat
target
.
DrawTriangles
(
vs
,
is
,
emptyImage
,
op
)
}
}

// Draw draws the path by rendering its stroke or filling.

Draw draws the path by rendering its stroke or filling .


func (g *GeoM) String() string {
	return fmt.Sprintf("[[%f, %f, %f], [%f, %f, %f]]", g.a_1+1, g.b, g.tx, g.c, g.d_1+1, g.ty)
}

func ( g * GeoM ) String ( ) string { return fmt . Sprintf ( " " , g . a_1 + 1 , g . b , g . tx , g . c , g . d_1 + 1 , g . ty ) }

// String returns a string representation of GeoM.

String returns a string representation of GeoM .


func (g *GeoM) Concat(other GeoM) {
	a := (other.a_1+1)*(g.a_1+1) + other.b*g.c
	b := (other.a_1+1)*g.b + other.b*(g.d_1+1)
	tx := (other.a_1+1)*g.tx + other.b*g.ty + other.tx
	c := other.c*(g.a_1+1) + (other.d_1+1)*g.c
	d := other.c*g.b + (other.d_1+1)*(g.d_1+1)
	ty := other.c*g.tx + (other.d_1+1)*g.ty + other.ty

	g.a_1 = a - 1
	g.b = b
	g.c = c
	g.d_1 = d - 1
	g.tx = tx
	g.ty = ty
}

func ( g * GeoM ) Concat ( other GeoM ) { a := ( other . a_1 + 1 ) * ( g . a_1 + 1 ) + other . b * g . c b := ( other . a_1 + 1 ) * g . b + other . b * ( g . d_1 + 1 ) tx := ( other . a_1 + 1 ) * g . tx + other . b * g . ty + other . tx c := other . c * ( g . a_1 + 1 ) + ( other . d_1 + 1 ) * g . c d := other . c * g . b + ( other . d_1 + 1 ) * ( g . d_1 + 1 ) ty := other . c * g . tx + ( other . d_1 + 1 ) * g . ty + other . ty g . a_1 = a - 1 g . b = b g . c = c g . d_1 = d - 1 g . tx = tx g . ty = ty }

// Concat multiplies a geometry matrix with the other geometry matrix.
// This is same as muptiplying the matrix other and the matrix g in this order.

Concat multiplies a geometry matrix with the other geometry matrix . This is same as muptiplying the matrix other and the matrix g in this order .


func (g *GeoM) Rotate(theta float64) {
	if theta == 0 {
		return
	}

	sin64, cos64 := math.Sincos(theta)
	sin, cos := float32(sin64), float32(cos64)

	a := cos*(g.a_1+1) - sin*g.c
	b := cos*g.b - sin*(g.d_1+1)
	tx := cos*g.tx - sin*g.ty
	c := sin*(g.a_1+1) + cos*g.c
	d := sin*g.b + cos*(g.d_1+1)
	ty := sin*g.tx + cos*g.ty

	g.a_1 = a - 1
	g.b = b
	g.c = c
	g.d_1 = d - 1
	g.tx = tx
	g.ty = ty
}

func ( g * GeoM ) Rotate ( theta float64 ) { if theta == 0 { return } sin64 , cos64 := math . Sincos ( theta ) sin , cos := float32 ( sin64 ) , float32 ( cos64 ) a := cos * ( g . a_1 + 1 ) - sin * g . c b := cos * g . b - sin * ( g . d_1 + 1 ) tx := cos * g . tx - sin * g . ty c := sin * ( g . a_1 + 1 ) + cos * g . c d := sin * g . b + cos * ( g . d_1 + 1 ) ty := sin * g . tx + cos * g . ty g . a_1 = a - 1 g . b = b g . c = c g . d_1 = d - 1 g . tx = tx g . ty = ty }

// Rotate rotates the matrix by theta.
// The unit is radian.

Rotate rotates the matrix by theta . The unit is radian .


func (g *GeoM) Invert() {
	det := g.det()
	if det == 0 {
		panic("ebiten: g is not invertible")
	}

	a := (g.d_1 + 1) / det
	b := -g.b / det
	c := -g.c / det
	d := (g.a_1 + 1) / det
	tx := (-(g.d_1+1)*g.tx + g.b*g.ty) / det
	ty := (g.c*g.tx + -(g.a_1+1)*g.ty) / det

	g.a_1 = a - 1
	g.b = b
	g.c = c
	g.d_1 = d - 1
	g.tx = tx
	g.ty = ty
}

// Invert inverts the matrix.
// If g is not invertible, Invert panics.

Invert inverts the matrix . If g is not invertible Invert panics .


func ScaleGeo(x, y float64) GeoM {
	g := GeoM{}
	g.Scale(x, y)
	return g
}

func ScaleGeo ( x , y float64 ) GeoM { g := GeoM { } g . Scale ( x , y ) return g }

// ScaleGeo is deprecated as of 1.2.0-alpha. Use Scale instead.

ScaleGeo is deprecated as of 1 . 2 . 0 - alpha . Use Scale instead .


func TranslateGeo(tx, ty float64) GeoM {
	g := GeoM{}
	g.Translate(tx, ty)
	return g
}

func TranslateGeo ( tx , ty float64 ) GeoM { g := GeoM { } g . Translate ( tx , ty ) return g }

// TranslateGeo is deprecated as of 1.2.0-alpha. Use Translate instead.

TranslateGeo is deprecated as of 1 . 2 . 0 - alpha . Use Translate instead .


func RotateGeo(theta float64) GeoM {
	g := GeoM{}
	g.Rotate(theta)
	return g
}

func RotateGeo ( theta float64 ) GeoM { g := GeoM { } g . Rotate ( theta ) return g }

// RotateGeo is deprecated as of 1.2.0-alpha. Use Rotate instead.

RotateGeo is deprecated as of 1 . 2 . 0 - alpha . Use Rotate instead .


func newFramebufferFromTexture(context *context, texture textureNative, width, height int) (*framebuffer, error) {
	native, err := context.newFramebuffer(texture)
	if err != nil {
		return nil, err
	}
	return &framebuffer{
		native: native,
		width:  width,
		height: height,
	}, nil
}

func newFramebufferFromTexture ( context * context , texture textureNative , width , height int ) ( * framebuffer , error ) { native , err := context . newFramebuffer ( texture ) if err != nil { return nil , err } return & framebuffer { native : native , width : width , height : height , } , nil }

// newFramebufferFromTexture creates a framebuffer from the given texture.

newFramebufferFromTexture creates a framebuffer from the given texture .


func newScreenFramebuffer(context *context, width, height int) *framebuffer {
	return &framebuffer{
		native: context.getScreenFramebuffer(),
		width:  width,
		height: height,
	}
}

func newScreenFramebuffer ( context * context , width , height int ) * framebuffer { return & framebuffer { native : context . getScreenFramebuffer ( ) , width : width , height : height , } }

// newScreenFramebuffer creates a framebuffer for the screen.

newScreenFramebuffer creates a framebuffer for the screen .


func opaque(m image.Image) bool {
	if o, ok := m.(opaquer); ok {
		return o.Opaque()
	}
	b := m.Bounds()
	for y := b.Min.Y; y < b.Max.Y; y++ {
		for x := b.Min.X; x < b.Max.X; x++ {
			_, _, _, a := m.At(x, y).RGBA()
			if a != 0xffff {
				return false
			}
		}
	}
	return true
}

func opaque ( m image . Image ) bool { if o , ok := m . ( opaquer ) ; ok { return o . Opaque ( ) } b := m . Bounds ( ) for y := b . Min . Y ; y < b . Max . Y ; y ++ { for x := b . Min . X ; x < b . Max . X ; x ++ { _ , _ , _ , a := m . At ( x , y ) . RGBA ( ) if a != 0xffff { return false } } } return true }

// Returns whether or not the image is fully opaque.

Returns whether or not the image is fully opaque .


func (e *encoder) writeIDATs() {
	if e.err != nil {
		return
	}
	if e.bw == nil {
		e.bw = bufio.NewWriterSize(e, 1<<15)
	} else {
		e.bw.Reset(e)
	}
	e.err = e.writeImage(e.bw, e.m, e.cb, levelToZlib(e.enc.CompressionLevel))
	if e.err != nil {
		return
	}
	e.err = e.bw.Flush()
}

func ( e * encoder ) writeIDATs ( ) { if e . err != nil { return } if e . bw == nil { e . bw = bufio . NewWriterSize ( e , 1 << 15 ) } else { e . bw . Reset ( e ) } e . err = e . writeImage ( e . bw , e . m , e . cb , levelToZlib ( e . enc . CompressionLevel ) ) if e . err != nil { return } e . err = e . bw . Flush ( ) }

// Write the actual image data to one or more IDAT chunks.

Write the actual image data to one or more IDAT chunks .


func levelToZlib(l CompressionLevel) int {
	switch l {
	case DefaultCompression:
		return zlib.DefaultCompression
	case NoCompression:
		return zlib.NoCompression
	case BestSpeed:
		return zlib.BestSpeed
	case BestCompression:
		return zlib.BestCompression
	default:
		return zlib.DefaultCompression
	}
}

func levelToZlib ( l CompressionLevel ) int { switch l { case DefaultCompression : return zlib . DefaultCompression case NoCompression : return zlib . NoCompression case BestSpeed : return zlib . BestSpeed case BestCompression : return zlib . BestCompression default : return zlib . DefaultCompression } }

// This function is required because we want the zero value of
// Encoder.CompressionLevel to map to zlib.DefaultCompression.

This function is required because we want the zero value of Encoder . CompressionLevel to map to zlib . DefaultCompression .


func Encode(w io.Writer, m image.Image) error {
	var e Encoder
	return e.Encode(w, m)
}

func Encode ( w io . Writer , m image . Image ) error { var e Encoder return e . Encode ( w , m ) }

// Encode writes the Image m to w in PNG format. Any Image may be
// encoded, but images that are not image.NRGBA might be encoded lossily.

Encode writes the Image m to w in PNG format . Any Image may be encoded but images that are not image . NRGBA might be encoded lossily .