== python api doc ==

First commit to make some structure in doc/ directory.

- moved source/blender/python/doc -> doc/python_api
- moved source/gameengine/PyDoc/*.rst -> doc/python_api/rst
- modified accordingly sphinx_doc_gen.py and sphinx_doc_gen.sh
  (later on I'll try alternative/ scripts by neXyon as promised :)
- source/gameengine/PyDoc/ is still there because contains epydoc stuff for the bge, will ask more and look into it later
This commit is contained in:
Luca Bonavita
2010-10-13 10:42:33 +00:00
parent d058a9c8c3
commit 996efebbe3
28 changed files with 1014 additions and 26 deletions

View File

@@ -0,0 +1,201 @@
{%- block doctype -%}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
{%- endblock %}
{%- set script_files = script_files + [pathto("_static/jquery.sidebar.js", 1)] %}
{%- set reldelim1 = reldelim1 is not defined and ' &raquo;' or reldelim1 %}
{%- set reldelim2 = reldelim2 is not defined and ' •' or reldelim2 %}
{%- macro relbar() %}
<div class="subnav boxheader">
<ul class="noprint"><li><a href="http://www.blender.org/development/coding-guides/">Coding Guides</a></li><li></li><li><a href="http://www.blender.org/development/report-a-bug/">Report a Bug</a></li><li></li><li><a href="http://www.blender.org/development/submit-a-patch/">Submit a Patch</a></li><li></li><li><a href="http://www.blender.org/development/release-logs/">Release Logs</a></li><li></li><li><a href="http://www.blender.org/development/current-projects/">Current Projects</a></li><li></li><li><a href="http://www.blender.org/development/architecture/">Architecture</a></li><li></li><li><a href="http://www.blender.org/development/building-blender/">Building Blender</a></li><li></li><li class="subnav-active"><a href="http://www.blender.org/documentation/250PythonDoc/contents.html">PyAPI</a></li><li></li><li><a href="http://wiki.blender.org/index.php/Main_Page">Wiki</a></li></ul>
</div>
<div class="related subnav">
<h3>{{ _('Navigation') }}</h3>
<ul>
{%- for rellink in rellinks %}
<li class="right">
<a href="{{ pathto(rellink[0]) }}" title="{{ rellink[1]|striptags }}"
{{ accesskey(rellink[2]) }}>{{ rellink[3] }}</a>
{%- if not loop.first %}{{ reldelim2 }}{% endif %}</li>
{%- endfor %}
{%- block rootrellink %}
<li><a href="{{ pathto(master_doc) }}">{{ shorttitle|e }}</a>{{ reldelim1 }}</li>
{%- endblock %}
{%- for parent in parents %}
<li><a href="{{ parent.link|e }}" {% if loop.last %}{{ accesskey("U") }}{% endif %}>{{ parent.title }}</a>{{ reldelim1 }}</li>
{%- endfor %}
{%- block relbaritems %} {% endblock %}
</ul>
</div>
{%- endmacro %}
{%- macro sidebar() %}
{%- if not embedded %}{% if not theme_nosidebar|tobool %}
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
{%- block sidebarlogo %}
{%- if logo %}
<p class="logo"><a href="{{ pathto(master_doc) }}">
<img class="logo" src="{{ pathto('_static/' + logo, 1) }}" alt="Logo"/>
</a></p>
{%- endif %}
{%- endblock %}
{%- block sidebartoc %}
{%- if display_toc %}
<h3><a href="{{ pathto(master_doc) }}">{{ _('Table Of Contents') }}</a></h3>
{{ toc }}
{%- endif %}
{%- endblock %}
{%- block sidebarrel %}
{%- if prev %}
<h4>{{ _('Previous topic') }}</h4>
<p class="topless"><a href="{{ prev.link|e }}"
title="{{ _('previous chapter') }}">{{ prev.title }}</a></p>
{%- endif %}
{%- if next %}
<h4>{{ _('Next topic') }}</h4>
<p class="topless"><a href="{{ next.link|e }}"
title="{{ _('next chapter') }}">{{ next.title }}</a></p>
{%- endif %}
{%- endblock %}
{%- block sidebarsourcelink %}
{%- if show_source and has_source and sourcename %}
<h3>{{ _('This Page') }}</h3>
<ul class="this-page-menu">
<li><a href="{{ pathto('_sources/' + sourcename, true)|e }}"
rel="nofollow">{{ _('Show Source') }}</a></li>
</ul>
{%- endif %}
{%- endblock %}
{%- if customsidebar %}
{% include customsidebar %}
{%- endif %}
{%- block sidebarsearch %}
{%- if pagename != "search" %}
<div id="searchbox" style="display: none">
<h3>{{ _('Quick search') }}</h3>
<form class="search" action="{{ pathto('search') }}" method="get">
<input type="text" name="q" size="18" />
<input type="submit" value="{{ _('Go') }}" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip">
{{ _('Enter search terms or a module, class or function name.') }}
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
{%- endif %}
{%- endblock %}
</div>
</div>
{%- endif %}{% endif %}
{%- endmacro %}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
{{ metatags }}
{%- if not embedded and docstitle %}
{%- set titlesuffix = " &mdash; "|safe + docstitle|e %}
{%- else %}
{%- set titlesuffix = "" %}
{%- endif %}
<title>{{ title|striptags }}{{ titlesuffix }}</title>
<link rel="stylesheet" href="{{ pathto('_static/' + style, 1) }}" type="text/css" />
<link rel="stylesheet" href="{{ pathto('_static/pygments.css', 1) }}" type="text/css" />
{%- if not embedded %}
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '{{ pathto("", 1) }}',
VERSION: '{{ release|e }}',
COLLAPSE_MODINDEX: false,
FILE_SUFFIX: '{{ file_suffix }}',
HAS_SOURCE: {{ has_source|lower }}
};
</script>
{%- for scriptfile in script_files %}
<script type="text/javascript" src="{{ pathto(scriptfile, 1) }}"></script>
{%- endfor %}
{%- if use_opensearch %}
<link rel="search" type="application/opensearchdescription+xml"
title="{% trans docstitle=docstitle|e %}Search within {{ docstitle }}{% endtrans %}"
href="{{ pathto('_static/opensearch.xml', 1) }}"/>
{%- endif %}
{%- if favicon %}
<link rel="shortcut icon" href="{{ pathto('_static/' + favicon, 1) }}"/>
{%- endif %}
{%- endif %}
{%- block linktags %}
{%- if hasdoc('about') %}
<link rel="author" title="{{ _('About these documents') }}" href="{{ pathto('about') }}" />
{%- endif %}
{%- if hasdoc('genindex') %}
<link rel="index" title="{{ _('Index') }}" href="{{ pathto('genindex') }}" />
{%- endif %}
{%- if hasdoc('search') %}
<link rel="search" title="{{ _('Search') }}" href="{{ pathto('search') }}" />
{%- endif %}
{%- if hasdoc('copyright') %}
<link rel="copyright" title="{{ _('Copyright') }}" href="{{ pathto('copyright') }}" />
{%- endif %}
<link rel="top" title="{{ docstitle|e }}" href="{{ pathto('index') }}" />
{%- if parents %}
<link rel="up" title="{{ parents[-1].title|striptags }}" href="{{ parents[-1].link|e }}" />
{%- endif %}
{%- if next %}
<link rel="next" title="{{ next.title|striptags }}" href="{{ next.link|e }}" />
{%- endif %}
{%- if prev %}
<link rel="prev" title="{{ prev.title|striptags }}" href="{{ prev.link|e }}" />
{%- endif %}
{%- endblock %}
{%- block extrahead %} {% endblock %}
</head>
<body>
{%- block header %}
<div class="noprint" id="navcontainer"><a href="http://www.blender.org/"><img width="140" height="50" title="blender.org home page" alt="blender.org home page" src="http://www.blender.org/fileadmin/site/_gfx/nav-home.png"></a><a href="http://www.blender.org/features-gallery/"><img width="140" height="50" title="Features &amp; Gallery" alt="Features &amp; Gallery" src="http://www.blender.org/fileadmin/site/_gfx/nav-features.png"></a><a href="http://www.blender.org/download/get-blender/"><img width="140" height="50" title="Download" alt="Download" src="http://www.blender.org/fileadmin/site/_gfx/nav-download.png"></a><a href="http://www.blender.org/education-help/"><img width="140" height="50" title="Tutorials &amp; Help" alt="Tutorials &amp; Help" src="http://www.blender.org/fileadmin/site/_gfx/nav-help.png"></a><a href="http://www.blender.org/community/user-community/"><img width="140" height="50" title="Community" alt="Community" src="http://www.blender.org/fileadmin/site/_gfx/nav-community.png"></a><a href="http://www.blender.org/development/"><img width="140" height="50" title="Development" alt="Development" src="http://www.blender.org/fileadmin/site/_gfx/nav-development-on.png"></a><a href="http://www.blender.org/e-shop/"><img width="140" height="50" title="e-Shop" alt="e-Shop" src="http://www.blender.org/fileadmin/site/_gfx/nav-eshop.png"></a></div>
{% endblock %}
<div class="document">
<div id="pageheader"></div>
{%- block relbar1 %}{{ relbar() }}{% endblock %}
{%- block sidebar1 %} {# possible location for sidebar #} {% endblock %}
{%- block document %}
<div class="documentwrapper">
{%- if not embedded %}{% if not theme_nosidebar|tobool %}
<div class="bodywrapper">
{%- endif %}{% endif %}
<div class="body">
{% block body %} {% endblock %}
</div>
{%- if not embedded %}{% if not theme_nosidebar|tobool %}
</div>
{%- endif %}{% endif %}
</div>
{%- endblock %}
{%- block sidebar2 %}{{ sidebar() }}{% endblock %}
<div class="clearer"></div>
{%- block footer %}
<div class="footer">
{%- if hasdoc('copyright') %}
{% trans path=pathto('copyright'), copyright=copyright|e %}&copy; <a href="{{ path }}">Copyright</a> {{ copyright }}.{% endtrans %}
{%- else %}
{% trans copyright=copyright|e %}&copy; Copyright {{ copyright }}.{% endtrans %}
{%- endif %}
{%- if last_updated %}
{% trans last_updated=last_updated|e %}Last updated on {{ last_updated }}.{% endtrans %}
{%- endif %}
{%- if show_sphinx %}
{% trans sphinx_version=sphinx_version|e %}Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> {{ sphinx_version }}.{% endtrans %}
{%- endif %}
</div><b class="round"><b id="r1"></b><b id="r2"></b><b id="r3"></b><b id="r4"></b></b>
{%- endblock %}
</div>
</body>
</html>

View File

@@ -0,0 +1,4 @@
{% extends "layout.html" %}
{% block body %}
{{ body }}
{% endblock %}

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@@ -0,0 +1,654 @@
/**
* Sphinx stylesheet -- default theme
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
@import url("basic.css");
/* -- page layout ----------------------------------------------------------- */
#navcontainer {
height: 50px;
margin: 0 auto;
position: relative;
width: 980px;
}
#navcontainer img {
width: 140px;
height: 50px;
}
#pageheader {
background-image:url("bg.png");
height:80px;
position:relative;
}
body {
font-family: {{ theme_bodyfont }};
font-size: 12px;
line-height: 145%;
background-color: {{ theme_footerbgcolor }};
color: {{ theme_textcolor }};
min-width: 980px;
margin: 0;
padding: 0;
}
div.document {
margin:20px auto 0;
position:relative;
text-align:left;
width:980px;
/* background-color: {{ theme_sidebarbgcolor }};*/
}
div.documentwrapper {
float: left;
width: 100%;
background-color: {{ theme_bgcolor }};
border-color: {{ theme_bordercolor }};
border-style:solid;
border-width:0 1px;
margin:0 auto;
min-height:30em;
padding:35px;
/* position:relative;*/
text-align:left;
width:908px;
}
div.bodywrapper {
margin: 0 0 0 230px;
}
div.body {
background-color: {{ theme_bgcolor }};
color: {{ theme_textcolor }};
padding: 0;
width: 640px;
}
{%- if theme_rightsidebar|tobool %}
div.bodywrapper {
margin: 0 230px 0 0;
}
{%- endif %}
div.footer {
background: #292929;
border-left: 1px solid #363636;
border-right: 1px solid #363636;
color: #ffffff;
/* width: 100%;*/
margin: 0 auto;
padding: 20px 20px 15px 35px;
text-align: center;
font-size: 75%;
}
div.footer+.round b {
display: block;
background: #292929;
width: auto;
}
div.footer+.round #r1 {
border-left: 1px solid #363636;
border-right: 1px solid #363636;
height: 2px;
margin: 0 1px;
}
div.footer+.round #r2 {
border-left: 1px solid #363636;
border-right: 1px solid #363636;
height: 1px;
margin: 0 2px;
}
div.footer+.round #r3 {
border-left: 1px solid #363636;
border-right: 1px solid #363636;
height: 1px;
margin: 0 3px;
}
div.footer+.round #r4 {
border-bottom: 1px solid #363636;
height: 0px;
margin: 0 5px;
}
div.footer a {
color: {{ theme_footertextcolor }};
text-decoration: underline;
}
.boxheader {
background-color:#3E4D5E;
}
.subnav {
height:auto !important;
min-height:15px;
padding:9px 0px 9px 37px;
position:relative;
}
div.related {
width:auto;
font-size:100%;
font-weight:400;
background-color: {{ theme_relbarbgcolor }};
line-height: 145%;
color: {{ theme_relbartextcolor }};
}
div.related li {
font-size:0.9em;
}
div.related li.right {
margin: 0;
word-spacing: 3px;
}
div.subnav li {
display:inline;
list-style-type:none;
margin:0;
padding:0 7px 0 0;
}
div.subnav ul {
display:inline;
margin:0;
padding:0;
}
.subnav a {
font-weight: bold;
color: #fff;
}
.subnav li.subnav-active a {
color:#F39410;
}
div.related a {
color: {{ theme_relbarlinkcolor }};
}
div.related a:active {
color: {{ theme_relbaractlinkcolor }};
}
div.sphinxsidebar {
width: 280px;
font-size: 100%;
{%- if theme_stickysidebar|tobool %}
/* top: 30px;*/
margin: 0;
position: absolute;
overflow: auto;
height: 100%;
{%- endif %}
{%- if theme_rightsidebar|tobool %}
float: right;
{%- if theme_stickysidebar|tobool %}
right: 0;
{%- endif %}
{%- endif %}
}
div.sphinxsidebarwrapper {
width: inherit;
padding: 0;
position: absolute;
margin-top: 35px;
font-size: 8pt;
}
div.sphinxsidebarwrapper.fixed {
position:fixed;
top:10px;
margin-top: 0;
}
{%- if theme_stickysidebar|tobool %}
/* this is nice, but it it leads to hidden headings when jumping
to an anchor */
/*
div.related {
position: fixed;
}
div.documentwrapper {
margin-top: 30px;
}
*/
{%- endif %}
div.sphinxsidebar h3 {
font-family: {{ theme_headfont }};
color: {{ theme_sidebartextcolor }};
font-size: 12px;
font-weight: bold;
background: #3E4D5E url("rnd.png") no-repeat top left;
height: 16px;
margin: 0;
padding: 10px 5px 10px 18px;
}
div.sphinxsidebar h3 a {
color: {{ theme_sidebartextcolor }};
}
div.sphinxsidebar h4 {
font-family: {{ theme_headfont }};
color: {{ theme_sidebartextcolor }};
background: #3E4D5E url("rnd.png") no-repeat top left;
height: 16px;
font-size: 12px;
font-weight: bold;
margin: 0;
padding: 10px 5px 10px 18px;
}
div.sphinxsidebar form {
margin: 0;
padding: 10px;
background-color: #292929;
{%- if theme_rightsidebar|tobool %}
border-right: 1px solid {{ theme_bordercolor }};
{%- endif %}
}
div.sphinxsidebar p {
background-color: #292929;
padding: 5px 10px 10px 10px;
color: {{ theme_sidebartextcolor }};
{%- if theme_rightsidebar|tobool %}
border-right: 1px solid {{ theme_bordercolor }};
{%- endif %}
margin-top: 0;
}
div.sphinxsidebar p.topless {
margin-bottom: 25px;
}
div.sphinxsidebar ul {
background-color: #292929;
margin: 0;
padding: 0;
color: {{ theme_sidebartextcolor }};
}
div.sphinxsidebar > div > ul {
margin-bottom: 25px;
padding:10px;
}
div.sphinxsidebar a {
color: {{ theme_sidebarlinkcolor }};
}
div.sphinxsidebar input {
border: 1px solid {{ theme_sidebarlinkcolor }};
font-family: sans-serif;
font-size: 1em;
}
/* -- body styles ----------------------------------------------------------- */
a {
color: {{ theme_linkcolor }};
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/*div.body h1,*/
div.body h2,
div.body h3,
div.body h4,
div.body h5,
div.body h6 {
font-family: {{ theme_headfont }};
background-color: {{ theme_headbgcolor }};
font-weight: bold;
color: {{ theme_headtextcolor }};
/* border-bottom: 1px solid #ccc;*/
margin: 20px -20px 10px -20px;
padding: 3px 0 3px 10px;
}
div.body h1 { margin-top: 0; font-size: 200%;
color:#FFFAE0;
font-family:"Helvetica","Arial",sans-serif;
font-size:34px;
font-weight:normal;
left:32px;
line-height:26px;
margin-top:0;
position:absolute;
top:36px;
}
div.body h2 { font-size: 160%; }
div.body h3 { font-size: 140%; }
div.body h4 { font-size: 120%; }
div.body h5 { font-size: 110%; }
div.body h6 { font-size: 100%; }
a.headerlink {
color: {{ theme_headlinkcolor }};
font-size: 0.8em;
padding: 0 4px 0 4px;
text-decoration: none;
}
h1:hover > a.headerlink {
display:none;
}
a.headerlink:hover {
background-color: {{ theme_headlinkcolor }};
color: white;
}
div.body p, div.body dd, div.body li {
text-align: justify;
line-height: 130%;
}
div.note, div.seealso, div.topic, div.warning {
color:white;
}
div.admonition p.admonition-title + p {
display: inline;
}
div.note {
background-color: #555;
border: 1px solid #ddd;
}
div.seealso {
background-color: #525241;
border: 1px solid #ff6;
}
div.topic {
background-color: #eee;
}
div.warning {
background-color: #B64444;
border: 1px solid #990606;
}
p.admonition-title {
display: inline;
}
p.admonition-title:after {
content: ":";
}
dl div.admonition {
border:medium none;
margin:0;
padding:2px 5px 2px 0;
}
dl.class > dd > div.warning p.admonition-title,
dl.class > dd > div.note p.admonition-title {
display:none;
}
dl.class > dd > div.admonition.warning p,
dl.class > dd > div.admonition.note p {
margin:0;
}
dl.class > dd > div.admonition.warning,
dl.class > dd > div.admonition.note {
margin-bottom:12px;
}
dl div.admonition.note p.admonition-title, dl div.admonition.warning p.admonition-title {
color:inherit;
}
dl div.admonition.warning p {
font-weight:bold;
line-height:150%;
}
dl div.admonition.warning p * {
font-weight:normal;
}
dl div.admonition p.admonition-title {
color:#555555;
display:block;
float:left;
margin:0;
padding-right:12px;
text-align:right;
width:90px;
}
dl div.admonition p.admonition-title+p, dl div.admonition p {
display:block;
margin:0 0 0 102px;
}
dl div.note {
background:none;
color:#E8E481;
}
dl div.warning {
background:none;
color:#FC3030;
}
dl div.seealso {
background:none;
}
dl div.admonition.seealso p+p {
color:#222;
}
dl div.seealso a {
margin-left:-1.3ex;
}
div.admonition.warning pre {
background: #0F0704;
color: #fc3030;
}
div.admonition pre {
margin: 6px 0;
overflow: visible;
white-space: pre-wrap;
}
pre {
padding: 10px;
background-color: #000;
color: #fff;
line-height: normal;
border: 0 solid white;
}
dl.function>dt, dl.method>dt {
text-indent:-118px;
padding-left: 118px;
}
dl.function>dt em, dl.method>dt em {
color: #97b9cf;
}
dl.function>dd em, dl.method>dd em {
color: #97b9cf;
font-weight:bold;
}
dl.function table.field-list tr:first-child td.field-body, dl.method table.field-list tr:first-child td.field-body {
color: #728c96;
}
dl.function>dt em:before, dl.method>dt em:before {
content: " ";
display: block;
}
dl.function>dd>p,dl.method>dd>p,dl.attribute>dd>p,
dl[class]>dd>ol,dl[class]>dd>ul {
color: #999;
}
dl.data>dt {
color:#08C659;
}
dl.data>dd>p {
color:#069643;
}
dl.class>dt {
color: #82a3c7;
}
dl.class>dd>p,dl.class>dd>ol,dl.class>dd>ul {
color: #637b96;
}
dl.function>dt,dl.method>dt,dl.attribute>dt {
color: #fcb100;
}
dl.function>dd>p,dl.method>dd>p,dl.attribute>dd>p,
dl.function>dd>p+ol,dl.method>dd>p+ol,dl.attribute>dd>p+ol,
dl.function>dd>p+ul,dl.method>dd>p+ul,dl.attribute>dd>p+ul {
color: #cb8f00;
}
dl.function>dd>p, dl.method>dd>p, dl.attribute>dd>p {
margin: 0 0 3px 102px;
}
dl.function>dd>p:first-child:before, dl.method>dd>p:first-child:before, dl.attribute>dd>p:first-child:before {
content:"Description:";
color:#555;
font-weight:bold;
font-style:normal;
width:90px;
display:inline-block;
margin-left:-102px;
text-align:right;
padding-right:12px;
}
dt:target, .highlight {
color: #444;
background: #333;
}
.highlight {
background: #E2C788;
}
h1 .highlight {
color:inherit;
background:inherit;
}
dl {
margin-bottom: 25px;
}
dd {
margin: 3px 0 10px 15px;
}
.field-body tt.literal {
font-weight: normal;
}
tt {
background-color: #444;
padding: 0 1px 0 1px;
font-size: 0.95em;
}
.warning tt {
background: #cc6262;
}
.note tt {
background: #444;
}
dl .warning tt {
background:#0F0704;
display:block;
}
dl .note tt {
background:#2C2A1B;
}
table.indextable tr.cap {
background-color: transparent;
}
col.field-name {
width:90px;
}
dd table {
margin-bottom: 0;
}
table.field-list th {
color:#555;
padding:0;
text-align:right;
}
table.field-list td.field-body {
color:#999999;
padding-left:12px;
}
table.field-list td.field-body ul.first {
padding-left:0;
list-style:none;
margin-left:0;
}
dl.function>dd>ol, dl.method>dd>ol, dl.attribute>dd>ol,
dl.function>dd>ul, dl.method>dd>ul, dl.attribute>dd>ul,
dl.function>dd>div[class|="highlight"], dl.method>dd>div[class|="highlight"],
dl.attribute>dd>div[class|="highlight"] {
margin-left:102px;
}
dl.function>dd>ol, dl.method>dd>ol, dl.attribute>dd>ol,
dl.function>dd>ul, dl.method>dd>ul, dl.attribute>dd>ul,
dl.class>dd>ol, dl.class>dd>ul {
padding-left:20px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,26 @@
$(document).ready(function () {
var top = $('.sphinxsidebarwrapper').offset().top - parseFloat($('.sphinxsidebarwrapper').css ('marginTop').replace(/auto/, 0));
var colheight = parseFloat($('.sphinxsidebarwrapper').css('height').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
//colheight is checked and according to its vaule the scrolling
//is triggered or not
if (colheight <= window.innerHeight) {
// if so, ad the fixed class
$('.sphinxsidebarwrapper').addClass('fixed');
} else {
// otherwise remove it
$('.sphinxsidebarwrapper').removeClass('fixed');
}
} else {
// otherwise remove it
$('.sphinxsidebarwrapper').removeClass('fixed');
}
});
});

View File

@@ -0,0 +1,61 @@
.hll { background-color: #ffffcc }
.c { color: #7f7f7f; font-style: italic } /* Comment */
.err { border: 1px solid #FF0000 } /* Error */
.k { color: #0088ff; font-weight: bold } /* Keyword */
.o { color: #993399 } /* Operator */
.cm { color: #7f7f7f; font-style: italic } /* Comment.Multiline */
.cp { color: #007020 } /* Comment.Preproc */
.c1 { color: #408090; font-style: italic } /* Comment.Single */
.cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */
.gd { color: #A00000 } /* Generic.Deleted */
.ge { font-style: italic } /* Generic.Emph */
.gr { color: #FF0000 } /* Generic.Error */
.gh { color: #000080; font-weight: bold } /* Generic.Heading */
.gi { color: #00A000 } /* Generic.Inserted */
.go { color: #303030 } /* Generic.Output */
.gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */
.gs { font-weight: bold } /* Generic.Strong */
.gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.gt { color: #0040D0 } /* Generic.Traceback */
.kc { color: #007020; font-weight: bold } /* Keyword.Constant */
.kd { color: #007020; font-weight: bold } /* Keyword.Declaration */
.kn { color: #FFFF32; font-weight: bold } /* Keyword.Namespace */
.kp { color: #007020 } /* Keyword.Pseudo */
.kr { color: #FFFF32; font-weight: bold } /* Keyword.Reserved */
.kt { color: #902000 } /* Keyword.Type */
.m { color: #00BAFF } /* Literal.Number */
.s { color: #B7C274 } /* Literal.String */
.na { color: #4070a0 } /* Name.Attribute */
.nb { color: #007020 } /* Name.Builtin */
.nc { color: #0e84b5; font-weight: bold } /* Name.Class */
.no { color: #60add5 } /* Name.Constant */
.nd { color: #555555; font-weight: bold } /* Name.Decorator */
.ni { color: #d55537; font-weight: bold } /* Name.Entity */
.ne { color: #007020 } /* Name.Exception */
.nf { color: #06287e } /* Name.Function */
.nl { color: #002070; font-weight: bold } /* Name.Label */
.nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */
.nt { color: #062873; font-weight: bold } /* Name.Tag */
.nv { color: #bb60d5 } /* Name.Variable */
.ow { color: #007020; font-weight: bold } /* Operator.Word */
.w { color: #bbbbbb } /* Text.Whitespace */
.mf { color: #00BAFF } /* Literal.Number.Float */
.mh { color: #00BAFF } /* Literal.Number.Hex */
.mi { color: #00BAFF } /* Literal.Number.Integer */
.mo { color: #00BAFF } /* Literal.Number.Oct */
.sb { color: #B7C274 } /* Literal.String.Backtick */
.sc { color: #B7C274 } /* Literal.String.Char */
.sd { color: #B7C274; font-style: italic } /* Literal.String.Doc */
.s2 { color: #B7C274 } /* Literal.String.Double */
.se { color: #B7C274; font-weight: bold } /* Literal.String.Escape */
.sh { color: #B7C274 } /* Literal.String.Heredoc */
.si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */
.sx { color: #c65d09 } /* Literal.String.Other */
.sr { color: #235388 } /* Literal.String.Regex */
.s1 { color: #4070a0 } /* Literal.String.Single */
.ss { color: #517918 } /* Literal.String.Symbol */
.bp { color: #007020 } /* Name.Builtin.Pseudo */
.vc { color: #bb60d5 } /* Name.Variable.Class */
.vg { color: #bb60d5 } /* Name.Variable.Global */
.vi { color: #bb60d5 } /* Name.Variable.Instance */
.il { color: #00BAFF } /* Literal.Number.Integer.Long */

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 B

View File

@@ -0,0 +1,30 @@
[theme]
inherit = basic
stylesheet = default.css
pygments_style = sphinx
[options]
rightsidebar = true
stickysidebar = true
footerbgcolor = #000000
footertextcolor = #ffffff
sidebarbgcolor = #1c4e63
sidebartextcolor = #ffffff
sidebarlinkcolor = #97b9cf
relbarbgcolor = #2C3845
relbartextcolor = #D3E0E9
relbarlinkcolor = #D3E0E9
relbaractlinkcolor = #f39410
bgcolor = #232323
bordercolor = #363636
textcolor = #ffffff
headbgcolor = #232323
headtextcolor = #ffffff
headlinkcolor = #97b9cf
linkcolor = #97b9cf
codebgcolor = #eeffcc
codetextcolor = #333333
bodyfont = "Lucida Grande","Lucida Sans Unicode","Lucida Sans","Lucida",Verdana,sans-serif
headfont = "Lucida Grande","Lucida Sans Unicode","Lucida Sans","Lucida",Verdana,sans-serif

1807
doc/python_api/epy/BGL.py Normal file
View File

@@ -0,0 +1,1807 @@
# Blender.BGL module (OpenGL wrapper)
"""
The Blender.BGL submodule (the OpenGL wrapper).
B{New}: some GLU functions: L{gluLookAt}, etc.
The Blender.BGL submodule
=========================
(when accessing it from the Game Engine use BGL instead of Blender.BGL)
This module wraps OpenGL constants and functions, making them available from
within Blender Python.
The complete list can be retrieved from the module itself, by listing its
contents: dir(Blender.BGL). A simple search on the net can point to more
than enough material to teach OpenGL programming, from books to many
collections of tutorials.
The "red book": "I{OpenGL Programming Guide: The Official Guide to Learning
OpenGL}" and the online NeHe tutorials are two of the best resources.
Example::
import Blender
from Blender.BGL import *
from Blender import Draw
R = G = B = 0
A = 1
title = "Testing BGL + Draw"
instructions = "Use mouse buttons or wheel to change the background color."
quitting = " Press ESC or q to quit."
len1 = Draw.GetStringWidth(title)
len2 = Draw.GetStringWidth(instructions + quitting)
#
def show_win():
glClearColor(R,G,B,A) # define color used to clear buffers
glClear(GL_COLOR_BUFFER_BIT) # use it to clear the color buffer
glColor3f(0.35,0.18,0.92) # define default color
glBegin(GL_POLYGON) # begin a vertex data list
glVertex2i(165, 158)
glVertex2i(252, 55)
glVertex2i(104, 128)
glEnd()
glColor3f(0.4,0.4,0.4) # change default color
glRecti(40, 96, 60+len1, 113)
glColor3f(1,1,1)
glRasterPos2i(50,100) # move cursor to x = 50, y = 100
Draw.Text(title) # draw this text there
glRasterPos2i(350,40) # move cursor again
Draw.Text(instructions + quitting) # draw another msg
glBegin(GL_LINE_LOOP) # begin a vertex-data list
glVertex2i(46,92)
glVertex2i(120,92)
glVertex2i(120,115)
glVertex2i(46,115)
glEnd() # close this list
#
def ev(evt, val): # event callback for Draw.Register()
global R,G,B,A # ... it handles input events
if evt == Draw.ESCKEY or evt == Draw.QKEY:
Draw.Exit() # this quits the script
elif not val: return
elif evt == Draw.LEFTMOUSE: R = 1 - R
elif evt == Draw.MIDDLEMOUSE: G = 1 - G
elif evt == Draw.RIGHTMOUSE: B = 1 - B
elif evt == Draw.WHEELUPMOUSE:
R += 0.1
if R > 1: R = 1
elif evt == Draw.WHEELDOWNMOUSE:
R -= 0.1
if R < 0: R = 0
else:
return # don't redraw if nothing changed
Draw.Redraw(1) # make changes visible.
#
Draw.Register(show_win, ev, None) # start the main loop
@note: you can use the L{Image} module and L{Image.Image} BPy object to load
and set textures. See L{Image.Image.glLoad} and L{Image.Image.glFree},
for example.
@see: U{www.opengl.org}
@see: U{nehe.gamedev.net}
"""
def glAccum(op, value):
"""
Operate on the accumulation buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/accum.html}
@type op: Enumerated constant
@param op: The accumulation buffer operation.
@type value: float
@param value: a value used in the accumulation buffer operation.
"""
def glAlphaFunc(func, ref):
"""
Specify the alpha test function
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/alphafunc.html}
@type func: Enumerated constant
@param func: Specifies the alpha comparison function.
@type ref: float
@param ref: The reference value that incoming alpha values are compared to.
Clamped between 0 and 1.
"""
def glAreTexturesResident(n, textures, residences):
"""
Determine if textures are loaded in texture memory
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/aretexturesresident.html}
@type n: int
@param n: Specifies the number of textures to be queried.
@type textures: Buffer object I{type GL_INT}
@param textures: Specifies an array containing the names of the textures to be queried
@type residences: Buffer object I{type GL_INT}(boolean)
@param residences: An array in which the texture residence status in returned.The residence status of a
texture named by an element of textures is returned in the corresponding element of residences.
"""
def glBegin(mode):
"""
Delimit the vertices of a primitive or a group of like primatives
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/begin.html}
@type mode: Enumerated constant
@param mode: Specifies the primitive that will be create from vertices between glBegin and
glEnd.
"""
def glBindTexture(target, texture):
"""
Bind a named texture to a texturing target
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/bindtexture.html}
@type target: Enumerated constant
@param target: Specifies the target to which the texture is bound.
@type texture: unsigned int
@param texture: Specifies the name of a texture.
"""
def glBitmap(width, height, xorig, yorig, xmove, ymove, bitmap):
"""
Draw a bitmap
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/bitmap.html}
@type width, height: int
@param width, height: Specify the pixel width and height of the bitmap image.
@type xorig, yorig: float
@param xorig, yorig: Specify the location of the origin in the bitmap image. The origin is measured
from the lower left corner of the bitmap, with right and up being the positive axes.
@type xmove, ymove: float
@param xmove, ymove: Specify the x and y offsets to be added to the current raster position after
the bitmap is drawn.
@type bitmap: Buffer object I{type GL_BYTE}
@param bitmap: Specifies the address of the bitmap image.
"""
def glBlendFunc(sfactor, dfactor):
"""
Specify pixel arithmetic
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/blendfunc.html}
@type sfactor: Enumerated constant
@param sfactor: Specifies how the red, green, blue, and alpha source blending factors are
computed.
@type dfactor: Enumerated constant
@param dfactor: Specifies how the red, green, blue, and alpha destination blending factors are
computed.
"""
def glCallList(list):
"""
Execute a display list
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/calllist.html}
@type list: unsigned int
@param list: Specifies the integer name of the display list to be executed.
"""
def glCallLists(n, type, lists):
"""
Execute a list of display lists
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/calllists.html}
@type n: int
@param n: Specifies the number of display lists to be executed.
@type type: Enumerated constant
@param type: Specifies the type of values in lists.
@type lists: Buffer object
@param lists: Specifies the address of an array of name offsets in the display list.
The pointer type is void because the offsets can be bytes, shorts, ints, or floats,
depending on the value of type.
"""
def glClear(mask):
"""
Clear buffers to preset values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clear.html}
@type mask: Enumerated constant(s)
@param mask: Bitwise OR of masks that indicate the buffers to be cleared.
"""
def glClearAccum(red, green, blue, alpha):
"""
Specify clear values for the accumulation buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearaccum.html}
@type red, green, blue, alpha: float
@param red, green, blue, alpha: Specify the red, green, blue, and alpha values used when the
accumulation buffer is cleared. The initial values are all 0.
"""
def glClearColor(red, green, blue, alpha):
"""
Specify clear values for the color buffers
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearcolor.html}
@type red, green, blue, alpha: float
@param red, green, blue, alpha: Specify the red, green, blue, and alpha values used when the
color buffers are cleared. The initial values are all 0.
"""
def glClearDepth(depth):
"""
Specify the clear value for the depth buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/cleardepth.html}
@type depth: int
@param depth: Specifies the depth value used when the depth buffer is cleared.
The initial value is 1.
"""
def glClearIndex(c):
"""
Specify the clear value for the color index buffers
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearindex.html}
@type c: float
@param c: Specifies the index used when the color index buffers are cleared.
The initial value is 0.
"""
def glClearStencil(s):
"""
Specify the clear value for the stencil buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearstencil.html}
@type s: int
@param s: Specifies the index used when the stencil buffer is cleared. The initial value is 0.
"""
def glClipPlane (plane, equation):
"""
Specify a plane against which all geometry is clipped
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clipplane.html}
@type plane: Enumerated constant
@param plane: Specifies which clipping plane is being positioned.
@type equation: Buffer object I{type GL_FLOAT}(double)
@param equation: Specifies the address of an array of four double- precision floating-point
values. These values are interpreted as a plane equation.
"""
def glColor (red, green, blue, alpha):
"""
B{glColor3b, glColor3d, glColor3f, glColor3i, glColor3s, glColor3ub, glColor3ui, glColor3us,
glColor4b, glColor4d, glColor4f, glColor4i, glColor4s, glColor4ub, glColor4ui, glColor4us,
glColor3bv, glColor3dv, glColor3fv, glColor3iv, glColor3sv, glColor3ubv, glColor3uiv,
glColor3usv, glColor4bv, glColor4dv, glColor4fv, glColor4iv, glColor4sv, glColor4ubv,
glColor4uiv, glColor4usv}
Set a new color.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/color.html}
@type red, green, blue, alpha: Depends on function prototype.
@param red, green, blue: Specify new red, green, and blue values for the current color.
@param alpha: Specifies a new alpha value for the current color. Included only in the
four-argument glColor4 commands. (With '4' colors only)
"""
def glColorMask(red, green, blue, alpha):
"""
Enable and disable writing of frame buffer color components
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/colormask.html}
@type red, green, blue, alpha: int (boolean)
@param red, green, blue, alpha: Specify whether red, green, blue, and alpha can or cannot be
written into the frame buffer. The initial values are all GL_TRUE, indicating that the
color components can be written.
"""
def glColorMaterial(face, mode):
"""
Cause a material color to track the current color
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/colormaterial.html}
@type face: Enumerated constant
@param face: Specifies whether front, back, or both front and back material parameters should
track the current color.
@type mode: Enumerated constant
@param mode: Specifies which of several material parameters track the current color.
"""
def glCopyPixels(x, y, width, height, type):
"""
Copy pixels in the frame buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/copypixels.html}
@type x, y: int
@param x, y: Specify the window coordinates of the lower left corner of the rectangular
region of pixels to be copied.
@type width, height: int
@param width,height: Specify the dimensions of the rectangular region of pixels to be copied.
Both must be non-negative.
@type type: Enumerated constant
@param type: Specifies whether color values, depth values, or stencil values are to be copied.
"""
def glCopyTexImage2D(target, level, internalformat, x, y, width, height, border):
"""
Copy pixels into a 2D texture image
@see: U{www.opengl.org/sdk/docs/man/xhtml/glCopyTexImage2D.xml}
@type target: Enumerated constant
@param target: Specifies the target texture.
@type level: int
@param level: Specifies the level-of-detail number. Level 0 is the base image level.
Level n is the nth mipmap reduction image.
@type internalformat: int
@param internalformat: Specifies the number of color components in the texture.
@type width: int
@type x, y: int
@param x, y:Specify the window coordinates of the first pixel that is copied
from the frame buffer. This location is the lower left corner of a rectangular
block of pixels.
@param width: Specifies the width of the texture image. Must be 2n+2(border) for
some integer n. All implementations support texture images that are at least 64
texels wide.
@type height: int
@param height: Specifies the height of the texture image. Must be 2m+2(border) for
some integer m. All implementations support texture images that are at least 64
texels high.
@type border: int
@param border: Specifies the width of the border. Must be either 0 or 1.
"""
def glCullFace(mode):
"""
Specify whether front- or back-facing facets can be culled
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/cullface.html}
@type mode: Enumerated constant
@param mode: Specifies whether front- or back-facing facets are candidates for culling.
"""
def glDeleteLists(list, range):
"""
Delete a contiguous group of display lists
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/deletelists.html}
@type list: unsigned int
@param list: Specifies the integer name of the first display list to delete
@type range: int
@param range: Specifies the number of display lists to delete
"""
def glDeleteTextures(n, textures):
"""
Delete named textures
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/deletetextures.html}
@type n: int
@param n: Specifies the number of textures to be deleted
@type textures: Buffer I{GL_INT}
@param textures: Specifies an array of textures to be deleted
"""
def glDepthFunc(func):
"""
Specify the value used for depth buffer comparisons
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/depthfunc.html}
@type func: Enumerated constant
@param func: Specifies the depth comparison function.
"""
def glDepthMask(flag):
"""
Enable or disable writing into the depth buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/depthmask.html}
@type flag: int (boolean)
@param flag: Specifies whether the depth buffer is enabled for writing. If flag is GL_FALSE,
depth buffer writing is disabled. Otherwise, it is enabled. Initially, depth buffer
writing is enabled.
"""
def glDepthRange(zNear, zFar):
"""
Specify mapping of depth values from normalized device coordinates to window coordinates
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/depthrange.html}
@type zNear: int
@param zNear: Specifies the mapping of the near clipping plane to window coordinates.
The initial value is 0.
@type zFar: int
@param zFar: Specifies the mapping of the far clipping plane to window coordinates.
The initial value is 1.
"""
def glDisable(cap):
"""
Disable server-side GL capabilities
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/enable.html}
@type cap: Enumerated constant
@param cap: Specifies a symbolic constant indicating a GL capability.
"""
def glDrawBuffer(mode):
"""
Specify which color buffers are to be drawn into
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawbuffer.html}
@type mode: Enumerated constant
@param mode: Specifies up to four color buffers to be drawn into.
"""
def glDrawPixels(width, height, format, type, pixels):
"""
Write a block of pixels to the frame buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html}
@type width, height: int
@param width, height: Specify the dimensions of the pixel rectangle to be
written into the frame buffer.
@type format: Enumerated constant
@param format: Specifies the format of the pixel data.
@type type: Enumerated constant
@param type: Specifies the data type for pixels.
@type pixels: Buffer object
@param pixels: Specifies a pointer to the pixel data.
"""
def glEdgeFlag (flag):
"""
B{glEdgeFlag, glEdgeFlagv}
Flag edges as either boundary or non-boundary
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/edgeflag.html}
@type flag: Depends of function prototype
@param flag: Specifies the current edge flag value.The initial value is GL_TRUE.
"""
def glEnable(cap):
"""
Enable server-side GL capabilities
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/enable.html}
@type cap: Enumerated constant
@param cap: Specifies a symbolic constant indicating a GL capability.
"""
def glEnd():
"""
Delimit the vertices of a primitive or group of like primitives
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/begin.html}
"""
def glEndList():
"""
Create or replace a display list
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/newlist.html}
"""
def glEvalCoord (u,v):
"""
B{glEvalCoord1d, glEvalCoord1f, glEvalCoord2d, glEvalCoord2f, glEvalCoord1dv, glEvalCoord1fv,
glEvalCoord2dv, glEvalCoord2fv}
Evaluate enabled one- and two-dimensional maps
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/evalcoord.html}
@type u: Depends on function prototype.
@param u: Specifies a value that is the domain coordinate u to the basis function defined
in a previous glMap1 or glMap2 command. If the function prototype ends in 'v' then
u specifies a pointer to an array containing either one or two domain coordinates. The first
coordinate is u. The second coordinate is v, which is present only in glEvalCoord2 versions.
@type v: Depends on function prototype. (only with '2' prototypes)
@param v: Specifies a value that is the domain coordinate v to the basis function defined
in a previous glMap2 command. This argument is not present in a glEvalCoord1 command.
"""
def glEvalMesh (mode, i1, i2):
"""
B{glEvalMesh1 or glEvalMesh2}
Compute a one- or two-dimensional grid of points or lines
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/evalmesh.html}
@type mode: Enumerated constant
@param mode: In glEvalMesh1, specifies whether to compute a one-dimensional
mesh of points or lines.
@type i1, i2: int
@param i1, i2: Specify the first and last integer values for the grid domain variable i.
"""
def glEvalPoint (i, j):
"""
B{glEvalPoint1 and glEvalPoint2}
Generate and evaluate a single point in a mesh
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/evalpoint.html}
@type i: int
@param i: Specifies the integer value for grid domain variable i.
@type j: int (only with '2' prototypes)
@param j: Specifies the integer value for grid domain variable j (glEvalPoint2 only).
"""
def glFeedbackBuffer (size, type, buffer):
"""
Controls feedback mode
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/feedbackbuffer.html}
@type size: int
@param size:Specifies the maximum number of values that can be written into buffer.
@type type: Enumerated constant
@param type:Specifies a symbolic constant that describes the information that
will be returned for each vertex.
@type buffer: Buffer object I{GL_FLOAT}
@param buffer: Returns the feedback data.
"""
def glFinish():
"""
Block until all GL execution is complete
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/finish.html}
"""
def glFlush():
"""
Force Execution of GL commands in finite time
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/flush.html}
"""
def glFog (pname, param):
"""
B{glFogf, glFogi, glFogfv, glFogiv}
Specify fog parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/fog.html}
@type pname: Enumerated constant
@param pname: Specifies a single-valued fog parameter. If the function prototype
ends in 'v' specifies a fog parameter.
@type param: Depends on function prototype.
@param param: Specifies the value or values to be assigned to pname. GL_FOG_COLOR
requires an array of four values. All other parameters accept an array containing
only a single value.
"""
def glFrontFace(mode):
"""
Define front- and back-facing polygons
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/frontface.html}
@type mode: Enumerated constant
@param mode: Specifies the orientation of front-facing polygons.
"""
def glFrustum(left, right, bottom, top, zNear, zFar):
"""
Multiply the current matrix by a perspective matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/frustum.html}
@type left, right: double (float)
@param left, right: Specify the coordinates for the left and right vertical
clipping planes.
@type top, bottom: double (float)
@param top, bottom: Specify the coordinates for the bottom and top horizontal
clipping planes.
@type zNear, zFar: double (float)
@param zNear, zFar: Specify the distances to the near and far depth clipping planes.
Both distances must be positive.
"""
def glGenLists(range):
"""
Generate a contiguous set of empty display lists
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/genlists.html}
@type range: int
@param range: Specifies the number of contiguous empty display lists to be generated.
"""
def glGenTextures(n, textures):
"""
Generate texture names
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gentextures.html}
@type n: int
@param n: Specifies the number of textures name to be generated.
@type textures: Buffer object I{type GL_INT}
@param textures: Specifies an array in which the generated textures names are stored.
"""
def glGet (pname, param):
"""
B{glGetBooleanv, glGetfloatv, glGetFloatv, glGetIntegerv}
Return the value or values of a selected parameter
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/get.html}
@type pname: Enumerated constant
@param pname: Specifies the parameter value to be returned.
@type param: Depends on function prototype.
@param param: Returns the value or values of the specified parameter.
"""
def glGetClipPlane(plane, equation):
"""
Return the coefficients of the specified clipping plane
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getclipplane.html}
@type plane: Enumerated constant
@param plane: Specifies a clipping plane. The number of clipping planes depends on the
implementation, but at least six clipping planes are supported. They are identified by
symbolic names of the form GL_CLIP_PLANEi where 0 < i < GL_MAX_CLIP_PLANES.
@type equation: Buffer object I{type GL_FLOAT}
@param equation: Returns four float (double)-precision values that are the coefficients of the
plane equation of plane in eye coordinates. The initial value is (0, 0, 0, 0).
"""
def glGetError():
"""
Return error information
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/geterror.html}
"""
def glGetLight (light, pname, params):
"""
B{glGetLightfv and glGetLightiv}
Return light source parameter values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getlight.html}
@type light: Enumerated constant
@param light: Specifies a light source. The number of possible lights depends on the
implementation, but at least eight lights are supported. They are identified by symbolic
names of the form GL_LIGHTi where 0 < i < GL_MAX_LIGHTS.
@type pname: Enumerated constant
@param pname: Specifies a light source parameter for light.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetMap (target, query, v):
"""
B{glGetMapdv, glGetMapfv, glGetMapiv}
Return evaluator parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getmap.html}
@type target: Enumerated constant
@param target: Specifies the symbolic name of a map.
@type query: Enumerated constant
@param query: Specifies which parameter to return.
@type v: Buffer object. Depends on function prototype.
@param v: Returns the requested data.
"""
def glGetMaterial (face, pname, params):
"""
B{glGetMaterialfv, glGetMaterialiv}
Return material parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getmaterial.html}
@type face: Enumerated constant
@param face: Specifies which of the two materials is being queried.
representing the front and back materials, respectively.
@type pname: Enumerated constant
@param pname: Specifies the material parameter to return.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetPixelMap (map, values):
"""
B{glGetPixelMapfv, glGetPixelMapuiv, glGetPixelMapusv}
Return the specified pixel map
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getpixelmap.html}
@type map: Enumerated constant
@param map: Specifies the name of the pixel map to return.
@type values: Buffer object. Depends on function prototype.
@param values: Returns the pixel map contents.
"""
def glGetPolygonStipple(mask):
"""
Return the polygon stipple pattern
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getpolygonstipple.html}
@type mask: Buffer object I{type GL_BYTE}
@param mask: Returns the stipple pattern. The initial value is all 1's.
"""
def glGetString(name):
"""
Return a string describing the current GL connection
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getstring.html}
@type name: Enumerated constant
@param name: Specifies a symbolic constant.
"""
def glGetTexEnv (target, pname, params):
"""
B{glGetTexEnvfv, glGetTexEnviv}
Return texture environment parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gettexenv.html}
@type target: Enumerated constant
@param target: Specifies a texture environment. Must be GL_TEXTURE_ENV.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of a texture environment parameter.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetTexGen (coord, pname, params):
"""
B{glGetTexGendv, glGetTexGenfv, glGetTexGeniv}
Return texture coordinate generation parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gettexgen.html}
@type coord: Enumerated constant
@param coord: Specifies a texture coordinate.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of the value(s) to be returned.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetTexImage(target, level, format, type, pixels):
"""
Return a texture image
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getteximage.html}
@type target: Enumerated constant
@param target: Specifies which texture is to be obtained.
@type level: int
@param level: Specifies the level-of-detail number of the desired image.
Level 0 is the base image level. Level n is the nth mipmap reduction image.
@type format: Enumerated constant
@param format: Specifies a pixel format for the returned data.
@type type: Enumerated constant
@param type: Specifies a pixel type for the returned data.
@type pixels: Buffer object.
@param pixels: Returns the texture image. Should be a pointer to an array of the
type specified by type
"""
def glGetTexLevelParameter (target, level, pname, params):
"""
B{glGetTexLevelParameterfv, glGetTexLevelParameteriv}
return texture parameter values for a specific level of detail
@see: U{opengl.org/developers/documentation/man_pages/hardcopy/GL/html/gl/gettexlevelparameter.html}
@type target: Enumerated constant
@param target: Specifies the symbolic name of the target texture.
@type level: int
@param level: Specifies the level-of-detail number of the desired image.
Level 0 is the base image level. Level n is the nth mipmap reduction image.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of a texture parameter.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetTexParameter (target, pname, params):
"""
B{glGetTexParameterfv, glGetTexParameteriv}
Return texture parameter values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gettexparameter.html}
@type target: Enumerated constant
@param target: Specifies the symbolic name of the target texture.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name the target texture.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the texture parameters.
"""
def glHint(target, mode):
"""
Specify implementation-specific hints
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/hint.html}
@type target: Enumerated constant
@param target: Specifies a symbolic constant indicating the behavior to be
controlled.
@type mode: Enumerated constant
@param mode: Specifies a symbolic constant indicating the desired behavior.
"""
def glIndex (c):
"""
B{glIndexd, glIndexf, glIndexi, glIndexs, glIndexdv, glIndexfv, glIndexiv, glIndexsv}
Set the current color index
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/index_.html}
@type c: Buffer object. Depends on function prototype.
@param c: Specifies a pointer to a one element array that contains the new value for
the current color index.
"""
def glInitNames():
"""
Initialize the name stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/initnames.html}
"""
def glIsEnabled(cap):
"""
Test whether a capability is enabled
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/isenabled.html}
@type cap: Enumerated constant
@param cap: Specifies a constant representing a GL capability.
"""
def glIsList(list):
"""
Determine if a name corresponds to a display-list
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/islist.html}
@type list: unsigned int
@param list: Specifies a potential display-list name.
"""
def glIsTexture(texture):
"""
Determine if a name corresponds to a texture
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/istexture.html}
@type texture: unsigned int
@param texture: Specifies a value that may be the name of a texture.
"""
def glLight (light, pname, param):
"""
B{glLightf,glLighti, glLightfv, glLightiv}
Set the light source parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/light.html}
@type light: Enumerated constant
@param light: Specifies a light. The number of lights depends on the implementation,
but at least eight lights are supported. They are identified by symbolic names of the
form GL_LIGHTi where 0 < i < GL_MAX_LIGHTS.
@type pname: Enumerated constant
@param pname: Specifies a single-valued light source parameter for light.
@type param: Depends on function prototype.
@param param: Specifies the value that parameter pname of light source light will be set to.
If function prototype ends in 'v' specifies a pointer to the value or values that
parameter pname of light source light will be set to.
"""
def glLightModel (pname, param):
"""
B{glLightModelf, glLightModeli, glLightModelfv, glLightModeliv}
Set the lighting model parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/lightmodel.html}
@type pname: Enumerated constant
@param pname: Specifies a single-value light model parameter.
@type param: Depends on function prototype.
@param param: Specifies the value that param will be set to. If function prototype ends in 'v'
specifies a pointer to the value or values that param will be set to.
"""
def glLineStipple(factor, pattern):
"""
Specify the line stipple pattern
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/linestipple.html}
@type factor: int
@param factor: Specifies a multiplier for each bit in the line stipple pattern.
If factor is 3, for example, each bit in the pattern is used three times before
the next bit in the pattern is used. factor is clamped to the range [1, 256] and
defaults to 1.
@type pattern: unsigned short int
@param pattern: Specifies a 16-bit integer whose bit pattern determines which fragments
of a line will be drawn when the line is rasterized. Bit zero is used first; the default
pattern is all 1's.
"""
def glLineWidth(width):
"""
Specify the width of rasterized lines.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/linewidth.html}
@type width: float
@param width: Specifies the width of rasterized lines. The initial value is 1.
"""
def glListBase(base):
"""
Set the display-list base for glCallLists
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/listbase.html}
@type base: unsigned int
@param base: Specifies an integer offset that will be added to glCallLists
offsets to generate display-list names. The initial value is 0.
"""
def glLoadIdentity():
"""
Replace the current matrix with the identity matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/loadidentity.html}
"""
def glLoadMatrix (m):
"""
B{glLoadMatrixd, glLoadMatixf}
Replace the current matrix with the specified matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/loadmatrix.html}
@type m: Buffer object. Depends on function prototype.
@param m: Specifies a pointer to 16 consecutive values, which are used as the elements
of a 4x4 column-major matrix.
"""
def glLoadName(name):
"""
Load a name onto the name stack.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/loadname.html}
@type name: unsigned int
@param name: Specifies a name that will replace the top value on the name stack.
"""
def glLogicOp(opcode):
"""
Specify a logical pixel operation for color index rendering
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/logicop.html}
@type opcode: Enumerated constant
@param opcode: Specifies a symbolic constant that selects a logical operation.
"""
def glMap1 (target, u1, u2, stride, order, points):
"""
B{glMap1d, glMap1f}
Define a one-dimensional evaluator
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/map1.html}
@type target: Enumerated constant
@param target: Specifies the kind of values that are generated by the evaluator.
@type u1, u2: Depends on function prototype.
@param u1,u2: Specify a linear mapping of u, as presented to glEvalCoord1, to ^, t
he variable that is evaluated by the equations specified by this command.
@type stride: int
@param stride: Specifies the number of floats or float (double)s between the beginning
of one control point and the beginning of the next one in the data structure
referenced in points. This allows control points to be embedded in arbitrary data
structures. The only constraint is that the values for a particular control point must
occupy contiguous memory locations.
@type order: int
@param order: Specifies the number of control points. Must be positive.
@type points: Buffer object. Depends on function prototype.
@param points: Specifies a pointer to the array of control points.
"""
def glMap2 (target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points):
"""
B{glMap2d, glMap2f}
Define a two-dimensional evaluator
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/map2.html}
@type target: Enumerated constant
@param target: Specifies the kind of values that are generated by the evaluator.
@type u1, u2: Depends on function prototype.
@param u1,u2: Specify a linear mapping of u, as presented to glEvalCoord2, to ^, t
he variable that is evaluated by the equations specified by this command. Initially
u1 is 0 and u2 is 1.
@type ustride: int
@param ustride: Specifies the number of floats or float (double)s between the beginning
of control point R and the beginning of control point R ij, where i and j are the u
and v control point indices, respectively. This allows control points to be embedded
in arbitrary data structures. The only constraint is that the values for a particular
control point must occupy contiguous memory locations. The initial value of ustride is 0.
@type uorder: int
@param uorder: Specifies the dimension of the control point array in the u axis.
Must be positive. The initial value is 1.
@type v1, v2: Depends on function prototype.
@param v1, v2: Specify a linear mapping of v, as presented to glEvalCoord2, to ^,
one of the two variables that are evaluated by the equations specified by this command.
Initially, v1 is 0 and v2 is 1.
@type vstride: int
@param vstride: Specifies the number of floats or float (double)s between the beginning of control
point R and the beginning of control point R ij, where i and j are the u and v control
point(indices, respectively. This allows control points to be embedded in arbitrary data
structures. The only constraint is that the values for a particular control point must
occupy contiguous memory locations. The initial value of vstride is 0.
@type vorder: int
@param vorder: Specifies the dimension of the control point array in the v axis.
Must be positive. The initial value is 1.
@type points: Buffer object. Depends on function prototype.
@param points: Specifies a pointer to the array of control points.
"""
def glMapGrid (un, u1,u2 ,vn, v1, v2):
"""
B{glMapGrid1d, glMapGrid1f, glMapGrid2d, glMapGrid2f}
Define a one- or two-dimensional mesh
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/mapgrid.html}
@type un: int
@param un: Specifies the number of partitions in the grid range interval
[u1, u2]. Must be positive.
@type u1, u2: Depends on function prototype.
@param u1, u2: Specify the mappings for integer grid domain values i=0 and i=un.
@type vn: int
@param vn: Specifies the number of partitions in the grid range interval [v1, v2]
(glMapGrid2 only).
@type v1, v2: Depends on function prototype.
@param v1, v2: Specify the mappings for integer grid domain values j=0 and j=vn
(glMapGrid2 only).
"""
def glMaterial (face, pname, params):
"""
Specify material parameters for the lighting model.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/material.html}
@type face: Enumerated constant
@param face: Specifies which face or faces are being updated. Must be one of:
@type pname: Enumerated constant
@param pname: Specifies the single-valued material parameter of the face
or faces that is being updated. Must be GL_SHININESS.
@type params: int
@param params: Specifies the value that parameter GL_SHININESS will be set to.
If function prototype ends in 'v' specifies a pointer to the value or values that
pname will be set to.
"""
def glMatrixMode(mode):
"""
Specify which matrix is the current matrix.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/matrixmode.html}
@type mode: Enumerated constant
@param mode: Specifies which matrix stack is the target for subsequent matrix operations.
"""
def glMultMatrix (m):
"""
B{glMultMatrixd, glMultMatrixf}
Multiply the current matrix with the specified matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/multmatrix.html}
@type m: Buffer object. Depends on function prototype.
@param m: Points to 16 consecutive values that are used as the elements of a 4x4 column
major matrix.
"""
def glNewList(list, mode):
"""
Create or replace a display list
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/newlist.html}
@type list: unsigned int
@param list: Specifies the display list name
@type mode: Enumerated constant
@param mode: Specifies the compilation mode.
"""
def glNormal3 (nx, ny, nz, v):
"""
B{Normal3b, Normal3bv, Normal3d, Normal3dv, Normal3f, Normal3fv, Normal3i, Normal3iv,
Normal3s, Normal3sv}
Set the current normal vector
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/normal.html}
@type nx, ny, nz: Depends on function prototype. (non - 'v' prototypes only)
@param nx, ny, nz: Specify the x, y, and z coordinates of the new current normal.
The initial value of the current normal is the unit vector, (0, 0, 1).
@type v: Buffer object. Depends on function prototype. ('v' prototypes)
@param v: Specifies a pointer to an array of three elements: the x, y, and z coordinates
of the new current normal.
"""
def glOrtho(left, right, bottom, top, zNear, zFar):
"""
Multiply the current matrix with an orthographic matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/ortho.html}
@type left, right: double (float)
@param left, right: Specify the coordinates for the left and
right vertical clipping planes.
@type bottom, top: double (float)
@param bottom, top: Specify the coordinates for the bottom and top
horizontal clipping planes.
@type zNear, zFar: double (float)
@param zNear, zFar: Specify the distances to the nearer and farther
depth clipping planes. These values are negative if the plane is to be behind the viewer.
"""
def glPassThrough(token):
"""
Place a marker in the feedback buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/passthrough.html}
@type token: float
@param token: Specifies a marker value to be placed in the feedback
buffer following a GL_PASS_THROUGH_TOKEN.
"""
def glPixelMap (map, mapsize, values):
"""
B{glPixelMapfv, glPixelMapuiv, glPixelMapusv}
Set up pixel transfer maps
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pixelmap.html}
@type map: Enumerated constant
@param map: Specifies a symbolic map name.
@type mapsize: int
@param mapsize: Specifies the size of the map being defined.
@type values: Buffer object. Depends on function prototype.
@param values: Specifies an array of mapsize values.
"""
def glPixelStore (pname, param):
"""
B{glPixelStoref, glPixelStorei}
Set pixel storage modes
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pixelstore.html}
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of the parameter to be set.
Six values affect the packing of pixel data into memory.
Six more affect the unpacking of pixel data from memory.
@type param: Depends on function prototype.
@param param: Specifies the value that pname is set to.
"""
def glPixelTransfer (pname, param):
"""
B{glPixelTransferf, glPixelTransferi}
Set pixel transfer modes
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pixeltransfer.html}
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of the pixel transfer parameter to be set.
@type param: Depends on function prototype.
@param param: Specifies the value that pname is set to.
"""
def glPixelZoom(xfactor, yfactor):
"""
Specify the pixel zoom factors
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pixelzoom.html}
@type xfactor, yfactor: float
@param xfactor, yfactor: Specify the x and y zoom factors for pixel write operations.
"""
def glPointSize(size):
"""
Specify the diameter of rasterized points
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pointsize.html}
@type size: float
@param size: Specifies the diameter of rasterized points. The initial value is 1.
"""
def glPolygonMode(face, mode):
"""
Select a polygon rasterization mode
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/polygonmode.html}
@type face: Enumerated constant
@param face: Specifies the polygons that mode applies to.
Must be GL_FRONT for front-facing polygons, GL_BACK for back- facing polygons,
or GL_FRONT_AND_BACK for front- and back-facing polygons.
@type mode: Enumerated constant
@param mode: Specifies how polygons will be rasterized.
The initial value is GL_FILL for both front- and back- facing polygons.
"""
def glPolygonOffset(factor, units):
"""
Set the scale and units used to calculate depth values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/polygonoffset.html}
@type factor: float
@param factor: Specifies a scale factor that is used to create a variable depth
offset for each polygon. The initial value is 0.
@type units: float
@param units: Is multiplied by an implementation-specific value to create a constant
depth offset. The initial value is 0.
"""
def glPolygonStipple(mask):
"""
Set the polygon stippling pattern
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/polygonstipple.html}
@type mask: Buffer object I{type GL_BYTE}
@param mask: Specifies a pointer to a 32x32 stipple pattern that will be unpacked
from memory in the same way that glDrawPixels unpacks pixels.
"""
def glPopAttrib():
"""
Pop the server attribute stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushattrib.html}
"""
def glPopClientAttrib():
"""
Pop the client attribute stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushclientattrib.html}
"""
def glPopMatrix():
"""
Pop the current matrix stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushmatrix.html}
"""
def glPopName():
"""
Pop the name stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushname.html}
"""
def glPrioritizeTextures(n, textures, priorities):
"""
Set texture residence priority
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/prioritizetextures.html}
@type n: int
@param n:Specifies the number of textures to be prioritized.
@type textures: Buffer I{type GL_INT}
@param textures: Specifies an array containing the names of the textures to be prioritized.
@type priorities: Buffer I{type GL_FLOAT}
@param priorities: Specifies an array containing the texture priorities. A priority given
in an element of priorities applies to the texture named by the corresponding element of textures.
"""
def glPushAttrib(mask):
"""
Push the server attribute stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushattrib.html}
@type mask: Enumerated constant(s)
@param mask: Specifies a mask that indicates which attributes to save.
"""
def glPushClientAttrib(mask):
"""
Push the client attribute stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushclientattrib.html}
@type mask: Enumerated constant(s)
@param mask: Specifies a mask that indicates which attributes to save.
"""
def glPushMatrix():
"""
Push the current matrix stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushmatrix.html}
"""
def glPushName(name):
"""
Push the name stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushname.html}
@type name: unsigned int
@param name: Specifies a name that will be pushed onto the name stack.
"""
def glRasterPos (x,y,z,w):
"""
B{glRasterPos2d, glRasterPos2f, glRasterPos2i, glRasterPos2s, glRasterPos3d,
glRasterPos3f, glRasterPos3i, glRasterPos3s, glRasterPos4d, glRasterPos4f,
glRasterPos4i, glRasterPos4s, glRasterPos2dv, glRasterPos2fv, glRasterPos2iv,
glRasterPos2sv, glRasterPos3dv, glRasterPos3fv, glRasterPos3iv, glRasterPos3sv,
glRasterPos4dv, glRasterPos4fv, glRasterPos4iv, glRasterPos4sv}
Specify the raster position for pixel operations
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/rasterpos.html}
@type x, y, z, w: Depends on function prototype. (z and w for '3' and '4' prototypes only)
@param x, y, z, w: Specify the x,y,z, and w object coordinates (if present) for the
raster position. If function prototype ends in 'v' specifies a pointer to an array of two,
three, or four elements, specifying x, y, z, and w coordinates, respectively.
@note:
If you are drawing to the 3d view with a Scriptlink of a space handler
the zoom level of the panels will scale the glRasterPos by the view matrix.
so a X of 10 will not always offset 10 pixels as you would expect.
To work around this get the scale value of the view matrix and use it to scale your pixel values.
Workaround::
import Blender
from Blender.BGL import *
xval, yval= 100, 40
# Get the scale of the view matrix
viewMatrix = Buffer(GL_FLOAT, 16)
glGetFloatv(GL_MODELVIEW_MATRIX, viewMatrix)
f = 1/viewMatrix[0]
glRasterPos2f(xval*f, yval*f) # Instead of the usual glRasterPos2i(xval, yval)
"""
def glReadBuffer(mode):
"""
Select a color buffer source for pixels.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/readbuffer.html}
@type mode: Enumerated constant
@param mode: Specifies a color buffer.
"""
def glReadPixels(x, y, width, height, format, type, pixels):
"""
Read a block of pixels from the frame buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/readpixels.html}
@type x, y: int
@param x, y:Specify the window coordinates of the first pixel that is read
from the frame buffer. This location is the lower left corner of a rectangular
block of pixels.
@type width, height: int
@param width, height: Specify the dimensions of the pixel rectangle. width and
height of one correspond to a single pixel.
@type format: Enumerated constant
@param format: Specifies the format of the pixel data.
@type type: Enumerated constant
@param type: Specifies the data type of the pixel data.
@type pixels: Buffer object
@param pixels: Returns the pixel data.
"""
def glRect (x1,y1,x2,y2,v1,v2):
"""
B{glRectd, glRectf, glRecti, glRects, glRectdv, glRectfv, glRectiv, glRectsv}
Draw a rectangle
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/rect.html}
@type x1, y1: Depends on function prototype. (for non 'v' prototypes only)
@param x1, y1: Specify one vertex of a rectangle
@type x2, y2: Depends on function prototype. (for non 'v' prototypes only)
@param x2, y2: Specify the opposite vertex of the rectangle
@type v1, v2: Depends on function prototype. (for 'v' prototypes only)
@param v1, v2: Specifies a pointer to one vertex of a rectangle and the pointer
to the opposite vertex of the rectangle
"""
def glRenderMode(mode):
"""
Set rasterization mode
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/rendermode.html}
@type mode: Enumerated constant
@param mode: Specifies the rasterization mode.
"""
def glRotate (angle, x, y, z):
"""
B{glRotated, glRotatef}
Multiply the current matrix by a rotation matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/rotate.html}
@type angle: Depends on function prototype.
@param angle: Specifies the angle of rotation in degrees.
@type x, y, z: Depends on function prototype.
@param x, y, z: Specify the x, y, and z coordinates of a vector respectively.
"""
def glScale (x,y,z):
"""
B{glScaled, glScalef}
Multiply the current matrix by a general scaling matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/scale.html}
@type x, y, z: Depends on function prototype.
@param x, y, z: Specify scale factors along the x, y, and z axes, respectively.
"""
def glScissor(x,y,width,height):
"""
Define the scissor box
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/scissor.html}
@type x, y: int
@param x, y: Specify the lower left corner of the scissor box. Initially (0, 0).
@type width, height: int
@param width height: Specify the width and height of the scissor box. When a
GL context is first attached to a window, width and height are set to the
dimensions of that window.
"""
def glSelectBuffer(size, buffer):
"""
Establish a buffer for selection mode values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/selectbuffer.html}
@type size: int
@param size: Specifies the size of buffer
@type buffer: Buffer I{type GL_INT}
@param buffer: Returns the selection data
"""
def glShadeModel(mode):
"""
Select flat or smooth shading
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/shademodel.html}
@type mode: Enumerated constant
@param mode: Specifies a symbolic value representing a shading technique.
"""
def glStencilFuc(func, ref, mask):
"""
Set function and reference value for stencil testing
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/stencilfunc.html}
@type func: Enumerated constant
@param func:Specifies the test function.
@type ref: int
@param ref:Specifies the reference value for the stencil test. ref is clamped to
the range [0,2n-1], where n is the number of bitplanes in the stencil buffer.
The initial value is 0.
@type mask: unsigned int
@param mask:Specifies a mask that is ANDed with both the reference value and
the stored stencil value when the test is done. The initial value is all 1's.
"""
def glStencilMask(mask):
"""
Control the writing of individual bits in the stencil planes
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/stencilmask.html}
@type mask: unsigned int
@param mask: Specifies a bit mask to enable and disable writing of individual bits
in the stencil planes. Initially, the mask is all 1's.
"""
def glStencilOp(fail, zfail, zpass):
"""
Set stencil test actions
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/stencilop.html}
@type fail: Enumerated constant
@param fail: Specifies the action to take when the stencil test fails.
The initial value is GL_KEEP.
@type zfail: Enumerated constant
@param zfail: Specifies the stencil action when the stencil test passes, but the
depth test fails. zfail accepts the same symbolic constants as fail.
The initial value is GL_KEEP.
@type zpass: Enumerated constant
@param zpass: Specifies the stencil action when both the stencil test and the
depth test pass, or when the stencil test passes and either there is no depth
buffer or depth testing is not enabled. zpass accepts the same symbolic constants
as fail. The initial value is GL_KEEP.
"""
def glTexCoord (s,t,r,q,v):
"""
B{glTexCoord1d, glTexCoord1f, glTexCoord1i, glTexCoord1s, glTexCoord2d, glTexCoord2f,
glTexCoord2i, glTexCoord2s, glTexCoord3d, glTexCoord3f, glTexCoord3i, glTexCoord3s,
glTexCoord4d, glTexCoord4f, glTexCoord4i, glTexCoord4s, glTexCoord1dv, glTexCoord1fv,
glTexCoord1iv, glTexCoord1sv, glTexCoord2dv, glTexCoord2fv, glTexCoord2iv,
glTexCoord2sv, glTexCoord3dv, glTexCoord3fv, glTexCoord3iv, glTexCoord3sv,
glTexCoord4dv, glTexCoord4fv, glTexCoord4iv, glTexCoord4sv}
Set the current texture coordinates
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texcoord.html}
@type s, t, r, q: Depends on function prototype. (r and q for '3' and '4' prototypes only)
@param s, t, r, q: Specify s, t, r, and q texture coordinates. Not all parameters are
present in all forms of the command.
@type v: Buffer object. Depends on function prototype. (for 'v' prototypes only)
@param v: Specifies a pointer to an array of one, two, three, or four elements,
which in turn specify the s, t, r, and q texture coordinates.
"""
def glTexEnv (target, pname, param):
"""
B{glTextEnvf, glTextEnvi, glTextEnvfv, glTextEnviv}
Set texture environment parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texenv.html}
@type target: Enumerated constant
@param target: Specifies a texture environment. Must be GL_TEXTURE_ENV.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of a single-valued texture environment
parameter. Must be GL_TEXTURE_ENV_MODE.
@type param: Depends on function prototype.
@param param: Specifies a single symbolic constant. If function prototype ends in 'v'
specifies a pointer to a parameter array that contains either a single symbolic
constant or an RGBA color
"""
def glTexGen (coord, pname, param):
"""
B{glTexGend, glTexGenf, glTexGeni, glTexGendv, glTexGenfv, glTexGeniv}
Control the generation of texture coordinates
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texgen.html}
@type coord: Enumerated constant
@param coord: Specifies a texture coordinate.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of the texture- coordinate generation function.
@type param: Depends on function prototype.
@param param: Specifies a single-valued texture generation parameter.
If function prototype ends in 'v' specifies a pointer to an array of texture
generation parameters. If pname is GL_TEXTURE_GEN_MODE, then the array must
contain a single symbolic constant. Otherwise, params holds the coefficients
for the texture-coordinate generation function specified by pname.
"""
def glTexImage1D(target, level, internalformat, width, border, format, type, pixels):
"""
Specify a one-dimensional texture image
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage1d.html}
@type target: Enumerated constant
@param target: Specifies the target texture.
@type level: int
@param level: Specifies the level-of-detail number. Level 0 is the base image level.
Level n is the nth mipmap reduction image.
@type internalformat: int
@param internalformat: Specifies the number of color components in the texture.
@type width: int
@param width: Specifies the width of the texture image. Must be 2n+2(border) for
some integer n. All implementations support texture images that are at least 64
texels wide. The height of the 1D texture image is 1.
@type border: int
@param border: Specifies the width of the border. Must be either 0 or 1.
@type format: Enumerated constant
@param format: Specifies the format of the pixel data.
@type type: Enumerated constant
@param type: Specifies the data type of the pixel data.
@type pixels: Buffer object.
@param pixels: Specifies a pointer to the image data in memory.
"""
def glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels):
"""
Specify a two-dimensional texture image
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html}
@type target: Enumerated constant
@param target: Specifies the target texture.
@type level: int
@param level: Specifies the level-of-detail number. Level 0 is the base image level.
Level n is the nth mipmap reduction image.
@type internalformat: int
@param internalformat: Specifies the number of color components in the texture.
@type width: int
@param width: Specifies the width of the texture image. Must be 2n+2(border) for
some integer n. All implementations support texture images that are at least 64
texels wide.
@type height: int
@param height: Specifies the height of the texture image. Must be 2m+2(border) for
some integer m. All implementations support texture images that are at least 64
texels high.
@type border: int
@param border: Specifies the width of the border. Must be either 0 or 1.
@type format: Enumerated constant
@param format: Specifies the format of the pixel data.
@type type: Enumerated constant
@param type: Specifies the data type of the pixel data.
@type pixels: Buffer object.
@param pixels: Specifies a pointer to the image data in memory.
"""
def glTexParameter (target, pname, param):
"""
B{glTexParameterf, glTexParameteri, glTexParameterfv, glTexParameteriv}
Set texture parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texparameter.html}
@type target: Enumerated constant
@param target: Specifies the target texture.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of a single-valued texture parameter.
@type param: Depends on function prototype.
@param param: Specifies the value of pname. If function prototype ends in 'v' specifies
a pointer to an array where the value or values of pname are stored.
"""
def glTranslate (x, y, z):
"""
B{glTranslatef, glTranslated}
Multiply the current matrix by a translation matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/translate.html}
@type x, y, z: Depends on function prototype.
@param x, y, z: Specify the x, y, and z coordinates of a translation vector.
"""
def glVertex (x,y,z,w,v):
"""
B{glVertex2d, glVertex2f, glVertex2i, glVertex2s, glVertex3d, glVertex3f, glVertex3i,
glVertex3s, glVertex4d, glVertex4f, glVertex4i, glVertex4s, glVertex2dv, glVertex2fv,
glVertex2iv, glVertex2sv, glVertex3dv, glVertex3fv, glVertex3iv, glVertex3sv, glVertex4dv,
glVertex4fv, glVertex4iv, glVertex4sv}
Specify a vertex
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/vertex.html}
@type x, y, z, w: Depends on function prototype (z and w for '3' and '4' prototypes only)
@param x, y, z, w: Specify x, y, z, and w coordinates of a vertex. Not all parameters
are present in all forms of the command.
@type v: Buffer object. Depends of function prototype (for 'v' prototypes only)
@param v: Specifies a pointer to an array of two, three, or four elements. The
elements of a two-element array are x and y; of a three-element array, x, y, and z;
and of a four-element array, x, y, z, and w.
"""
def glViewport(x,y,width,height):
"""
Set the viewport
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/viewport.html}
@type x, y: int
@param x, y: Specify the lower left corner of the viewport rectangle,
in pixels. The initial value is (0,0).
@type width, height: int
@param width, height: Specify the width and height of the viewport. When a GL context
is first attached to a window, width and height are set to the dimensions of that window.
"""
def gluPerspective(fovY, aspect, zNear, zFar):
"""
Set up a perspective projection matrix.
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5577288}
@type fovY: double
@param fovY: Specifies the field of view angle, in degrees, in the y direction.
@type aspect: double
@param aspect: Specifies the aspect ratio that determines the field of view in the x direction.
The aspect ratio is the ratio of x (width) to y (height).
@type zNear: double
@param zNear: Specifies the distance from the viewer to the near clipping plane (always positive).
@type zFar: double
@param zFar: Specifies the distance from the viewer to the far clipping plane (always positive).
"""
def gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz):
"""
Define a viewing transformation
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5573042}
@type eyex, eyey, eyez: double
@param eyex, eyey, eyez: Specifies the position of the eye point.
@type centerx, centery, centerz: double
@param centerx, centery, centerz: Specifies the position of the reference point.
@type upx, upy, upz: double
@param upx, upy, upz: Specifies the direction of the up vector.
"""
def gluOrtho2D(left, right, bottom, top):
"""
Define a 2-D orthographic projection matrix
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5578074}
@type left, right: double
@param left, right: Specify the coordinates for the left and right vertical clipping planes.
@type bottom, top: double
@param bottom, top: Specify the coordinates for the bottom and top horizontal clipping planes.
"""
def gluPickMatrix(x, y, width, height, viewport):
"""
Define a picking region
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5578074}
@type x, y: double
@param x, y: Specify the center of a picking region in window coordinates.
@type width, height: double
@param width, height: Specify the width and height, respectively, of the picking region in window coordinates.
@type viewport: Buffer object. [int]
@param viewport: Specifies the current viewport.
"""
def gluProject(objx, objy, objz, modelMatrix, projMatrix, viewport, winx, winy, winz):
"""
Map object coordinates to window coordinates.
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5578074}
@type objx, objy, objz: double
@param objx, objy, objz: Specify the object coordinates.
@type modelMatrix: Buffer object. [double]
@param modelMatrix: Specifies the current modelview matrix (as from a glGetDoublev call).
@type projMatrix: Buffer object. [double]
@param projMatrix: Specifies the current projection matrix (as from a glGetDoublev call).
@type viewport: Buffer object. [int]
@param viewport: Specifies the current viewport (as from a glGetIntegerv call).
@type winx, winy, winz: Buffer object. [double]
@param winx, winy, winz: Return the computed window coordinates.
"""
def gluUnProject(winx, winy, winz, modelMatrix, projMatrix, viewport, objx, objy, objz):
"""
Map object coordinates to window
coordinates.
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5582204}
@type winx, winy, winz: double
@param winx, winy, winz: Specify the window coordinates to be mapped.
@type modelMatrix: Buffer object. [double]
@param modelMatrix: Specifies the current modelview matrix (as from a glGetDoublev call).
@type projMatrix: Buffer object. [double]
@param projMatrix: Specifies the current projection matrix (as from a glGetDoublev call).
@type viewport: Buffer object. [int]
@param viewport: Specifies the current viewport (as from a glGetIntegerv call).
@type objx, objy, objz: Buffer object. [double]
@param objx, objy, objz: Return the computed object coordinates.
"""
class Buffer:
"""
The Buffer object is simply a block of memory that is delineated and initialized by the
user. Many OpenGL functions return data to a C-style pointer, however, because this
is not possible in python the Buffer object can be used to this end. Wherever pointer
notation is used in the OpenGL functions the Buffer object can be used in it's BGL
wrapper. In some instances the Buffer object will need to be initialized with the template
parameter, while in other instances the user will want to create just a blank buffer
which will be zeroed by default.
Example with Buffer::
import Blender
from Blender import BGL
myByteBuffer = BGL.Buffer(BGL.GL_BYTE, [32,32])
BGL.glGetPolygonStipple(myByteBuffer)
print myByteBuffer.dimensions
print myByteBuffer.list
sliceBuffer = myByteBuffer[0:16]
print sliceBuffer
@ivar list: The contents of the Buffer.
@ivar dimensions: The size of the Buffer.
"""
def __init__(type, dimensions, template = None):
"""
This will create a new Buffer object for use with other BGL OpenGL commands.
Only the type of argument to store in the buffer and the dimensions of the buffer
are necessary. Buffers are zeroed by default unless a template is supplied, in
which case the buffer is initialized to the template.
@type type: int
@param type: The format to store data in. The type should be one of
GL_BYTE, GL_SHORT, GL_INT, or GL_FLOAT.
@type dimensions: An int or sequence object specifying the dimensions of the buffer.
@param dimensions: If the dimensions are specified as an int a linear array will
be created for the buffer. If a sequence is passed for the dimensions, the buffer
becomes n-Dimensional, where n is equal to the number of parameters passed in the
sequence. Example: [256,2] is a two- dimensional buffer while [256,256,4] creates
a three- dimensional buffer. You can think of each additional dimension as a sub-item
of the dimension to the left. i.e. [10,2] is a 10 element array each with 2 sub-items.
[(0,0), (0,1), (1,0), (1,1), (2,0), ...] etc.
@type template: A python sequence object (optional)
@param template: A sequence of matching dimensions which will be used to initialize
the Buffer. If a template is not passed in all fields will be initialized to 0.
@rtype: Buffer object
@return: The newly created buffer as a PyObject.
"""

View File

@@ -0,0 +1,189 @@
# Blender.Geometry module and its subtypes
"""
The Blender.Geometry submodule.
Geometry
========
(when accessing it from the Game Engine use Geometry instead of Blender.Geometry)
This new module provides access to a geometry function.
"""
def Intersect(vec1, vec2, vec3, ray, orig, clip=1):
"""
Return the intersection between a ray and a triangle, if possible, return None otherwise.
@type vec1: Vector object.
@param vec1: A 3d vector, one corner of the triangle.
@type vec2: Vector object.
@param vec2: A 3d vector, one corner of the triangle.
@type vec3: Vector object.
@param vec3: A 3d vector, one corner of the triangle.
@type ray: Vector object.
@param ray: A 3d vector, the orientation of the ray. the length of the ray is not used, only the direction.
@type orig: Vector object.
@param orig: A 3d vector, the origin of the ray.
@type clip: integer
@param clip: if 0, don't restrict the intersection to the area of the triangle, use the infinite plane defined by the triangle.
@rtype: Vector object
@return: The intersection between a ray and a triangle, if possible, None otherwise.
"""
def TriangleArea(vec1, vec2, vec3):
"""
Return the area size of the 2D or 3D triangle defined.
@type vec1: Vector object.
@param vec1: A 2d or 3d vector, one corner of the triangle.
@type vec2: Vector object.
@param vec2: A 2d or 3d vector, one corner of the triangle.
@type vec3: Vector object.
@param vec3: A 2d or 3d vector, one corner of the triangle.
@rtype: float
@return: The area size of the 2D or 3D triangle defined.
"""
def TriangleNormal(vec1, vec2, vec3):
"""
Return the normal of the 3D triangle defined.
@type vec1: Vector object.
@param vec1: A 3d vector, one corner of the triangle.
@type vec2: Vector object.
@param vec2: A 3d vector, one corner of the triangle.
@type vec3: Vector object.
@param vec3: A 3d vector, one corner of the triangle.
@rtype: float
@return: The normal of the 3D triangle defined.
"""
def QuadNormal(vec1, vec2, vec3, vec4):
"""
Return the normal of the 3D quad defined.
@type vec1: Vector object.
@param vec1: A 3d vector, the first vertex of the quad.
@type vec2: Vector object.
@param vec2: A 3d vector, the second vertex of the quad.
@type vec3: Vector object.
@param vec3: A 3d vector, the third vertex of the quad.
@type vec4: Vector object.
@param vec4: A 3d vector, the fourth vertex of the quad.
@rtype: float
@return: The normal of the 3D quad defined.
"""
def LineIntersect(vec1, vec2, vec3, vec4):
"""
Return a tuple with the points on each line respectively closest to the other
(when both lines intersect, both vector hold the same value).
The lines are evaluated as infinite lines in space, the values returned may not be between the 2 points given for each line.
@type vec1: Vector object.
@param vec1: A 3d vector, one point on the first line.
@type vec2: Vector object.
@param vec2: A 3d vector, another point on the first line.
@type vec3: Vector object.
@param vec3: A 3d vector, one point on the second line.
@type vec4: Vector object.
@param vec4: A 3d vector, another point on the second line.
@rtype: (Vector object, Vector object)
@return: A tuple with the points on each line respectively closest to the other.
"""
def PolyFill(polylines):
"""
Takes a list of polylines and calculates triangles that would fill in the polylines.
Multiple lines can be used to make holes inside a polyline, or fill in 2 separate lines at once.
@type polylines: List of lists containing vectors, each representing a closed polyline.
@rtype: list
@return: a list if tuples each a tuple of 3 ints representing a triangle indexing the points given.
@note: 2D Vectors will have an assumed Z axis of zero, 4D Vectors W axis is ignored.
@note: The order of points in a polyline effect the direction returned triangles face, reverse the order of a polyline to flip the normal of returned faces.
I{B{Example:}}
The example below creates 2 polylines and fills them in with faces, then makes a mesh in the current scene::
import Blender
Vector= Blender.mathutils.Vector
# Outline of 5 points
polyline1= [Vector(-2.0, 1.0, 1.0), Vector(-1.0, 2.0, 1.0), Vector(1.0, 2.0, 1.0), Vector(1.0, -1.0, 1.0), Vector(-1.0, -1.0, 1.0)]
polyline2= [Vector(-1, 1, 1.0), Vector(0, 1, 1.0), Vector(0, 0, 1.0), Vector(-1.0, 0.0, 1.0)]
fill= Blender.Geometry.PolyFill([polyline1, polyline2])
# Make a new mesh and add the truangles into it
me= Blender.Mesh.New()
me.verts.extend(polyline1)
me.verts.extend(polyline2)
me.faces.extend(fill) # Add the faces, they reference the verts in polyline 1 and 2
scn = Blender.Scene.GetCurrent()
ob = scn.objects.new(me)
Blender.Redraw()
"""
def LineIntersect2D(vec1, vec2, vec3, vec4):
"""
Takes 2 lines vec1, vec2 for the 2 points of the first line and vec2, vec3 for the 2 points of the second line.
@rtype: Vector
@return: a 2D Vector for the intersection or None where there is no intersection.
"""
def ClosestPointOnLine(pt, vec1, vec2):
"""
Takes 2 lines vec1, vec2 for the 2 points of the first line and vec2, vec3 for the 2 points of the second line.
@rtype: tuple
@return: a tuple containing a vector and a float, the vector is the closest point on the line, the float is the position on the line, between 0 and 1 the point is on the line.
"""
def PointInTriangle2D(pt, tri_pt1, tri_pt2, tri_pt3):
"""
Takes 4 vectors (one for the test point and 3 for the triangle)
This is a 2d function so only X and Y are used, Z and W will be ignored.
@rtype: int
@return: 1 for a clockwise intersection, -1 for counter clockwise intersection, 0 when there is no intersection.
"""
def PointInQuad2D(pt, quad_pt1, quad_pt2, quad_pt3):
"""
Takes 5 vectors (one for the test point and 5 for the quad)
This is a 2d function so only X and Y are used, Z and W will be ignored.
@rtype: int
@return: 1 for a clockwise intersection, -1 for counter clockwise intersection, 0 when there is no intersection.
"""
def BoxPack2D(boxlist):
"""
Takes a list of 2D boxes and packs them into a square.
Each box in boxlist must be a list of at least 4 items - [x,y,w,h], after running this script,
the X and Y values in each box will be moved to packed, non overlapping locations.
Example::
# Make 500 random boxes, pack them and make a mesh from it
from Blender import Geometry, Scene, Mesh
import random
boxes = []
for i in xrange(500):
boxes.append( [0,0, random.random()+0.1, random.random()+0.1] )
boxsize = Geometry.BoxPack2D(boxes)
print 'BoxSize', boxsize
me = Mesh.New()
for x in boxes:
me.verts.extend([(x[0],x[1], 0), (x[0],x[1]+x[3], 0), (x[0]+x[2],x[1]+x[3], 0), (x[0]+x[2],x[1], 0) ])
v1= me.verts[-1]
v2= me.verts[-2]
v3= me.verts[-3]
v4= me.verts[-4]
me.faces.extend([(v1,v2,v3,v4)])
scn = Scene.GetCurrent()
scn.objects.new(me)
@note: Each boxlist item can be longer then 4, the extra items are ignored and stay untouched.
@rtype: tuple
@return: a tuple pair - (width, height) of all the packed boxes.
"""
def BezierInterp(vec_knot_1, vec_handle_1, vec_handle_2, vec_knot_2, resolution):
"""
Takes 4 vectors representing a bezier curve and returns a list of vector points.
@note: any vector size is supported, the largest dimension from the input will be used for all returned vectors/
@rtype: list
@return: a list of vectors the size of resolution including the start and end points (vec_knot_1 and vec_knot_2)
"""

View File

@@ -0,0 +1,132 @@
class IDGroup:
"""
The IDGroup Type
================
This type supports both iteration and the []
operator to get child ID properties.
You can also add new properties using the [] operator.
For example::
group['a float!'] = 0.0
group['an int!'] = 0
group['a string!'] = "hi!"
group['an array!'] = [0, 0, 1.0, 0]
group['a subgroup!] = {"float": 0.0, "an int": 1.0, "an array": [1, 2],
"another subgroup": {"a": 0.0, "str": "bleh"}}
Note that for arrays, the array type defaults to int unless a float is found
while scanning the template list; if any floats are found, then the whole
array is float. Note that double-precision floating point numbers are used for
python-created float ID properties and arrays (though the internal C api does
support single-precision floats, and the python code will read them).
You can also delete properties with the del operator. For example:
del group['property']
To get the type of a property, use the type() operator, for example::
if type(group['bleh']) == str: pass
To tell if the property is a group or array type, import the Blender.Types module and test
against IDGroupType and IDArrayType, like so::
from Blender.Types import IDGroupType, IDArrayType.
if type(group['bleghr']) == IDGroupType:
(do something)
@ivar name: The name of the property
@type name: string
"""
def pop(item):
"""
Pop an item from the group property.
@type item: string
@param item: The item name.
@rtype: can be dict, list, int, float or string.
@return: The removed property.
"""
def update(updatedict):
"""
Updates items in the dict, similar to normal python
dictionary method .update().
@type updatedict: dict
@param updatedict: A dict of simple types to derive updated/new IDProperties from.
@rtype: None
@return: None
"""
def keys():
"""
Returns a list of the keys in this property group.
@rtype: list of strings.
@return: a list of the keys in this property group.
"""
def values():
"""
Returns a list of the values in this property group.
Note that unless a value is itself a property group or an array, you
cannot change it by changing the values in this list, you must change them
in the parent property group.
For example,
group['some_property'] = new_value
. . .is correct, while,
values = group.values()
values[0] = new_value
. . .is wrong.
@rtype: list of strings.
@return: a list of the values in this property group.
"""
def iteritems():
"""
Implements the python dictionary iteritmes method.
For example::
for k, v in group.iteritems():
print "Property name: " + k
print "Property value: " + str(v)
@rtype: an iterator that spits out items of the form [key, value]
@return: an iterator.
"""
def convert_to_pyobject():
"""
Converts the entire property group to a purely python form.
@rtype: dict
@return: A python dictionary representing the property group
"""
class IDArray:
"""
The IDArray Type
================
@ivar type: returns the type of the array, can be either IDP_Int or IDP_Float
"""
def __getitem__(index):
pass
def __setitem__(index, value):
pass
def __len__():
pass

View File

@@ -0,0 +1,156 @@
# Blender.mathutils module and its subtypes
class Vector:
"""
@attention: Vector data can be wrapped or non-wrapped. When a object is wrapped it
means that the object will give you direct access to the data inside of blender. Modification
of this object will directly change the data inside of blender. To copy a wrapped object
you need to use the object's constructor. If you copy and object by assignment you will not get
a second copy but a second reference to the same data. Only certain functions will return
wrapped data. This will be indicated in the method description.
"""
def __init__(list = None):
"""
Create a new 2d, 3d, or 4d Vector object from a list of floating point numbers.
@note: that python uses higher precission floating point numbers, so values assigned to a vector may have some rounding error.
Example::
v = Vector(1,0,0)
v = Vector(myVec)
v = Vector(list)
@type list: PyList of float or int
@param list: The list of values for the Vector object. Can be a sequence or raw numbers.
Must be 2, 3, or 4 values. The list is mapped to the parameters as [x,y,z,w].
@rtype: Vector object.
@return: It depends wheter a parameter was passed:
- (list): Vector object initialized with the given values;
- (): An empty 3 dimensional vector.
"""
class Euler:
"""
The Euler object
================
This object gives access to Eulers in Blender.
@note: You can access a euler object like a sequence
- x = euler[0]
@note: Comparison operators can be done:
- ==, != test numeric values within epsilon
@attention: Euler data can be wrapped or non-wrapped. When a object is wrapped it
means that the object will give you direct access to the data inside of blender. Modification
of this object will directly change the data inside of blender. To copy a wrapped object
you need to use the object's constructor. If you copy and object by assignment you will not get
a second copy but a second reference to the same data. Only certain functions will return
wrapped data. This will be indicated in the method description.
"""
def __init__(list = None):
"""
Create a new euler object.
Example::
euler = Euler(45,0,0)
euler = Euler(myEuler)
euler = Euler(sequence)
@type list: PyList of float/int
@param list: 3d list to initialize euler
@rtype: Euler object
@return: Euler representing heading, pitch, bank.
@note: Values are in degrees.
"""
class Quaternion:
"""
The Quaternion object
=====================
This object gives access to Quaternions in Blender.
@note: Comparison operators can be done:
- ==, != test numeric values within epsilon
@note: Math can be performed on Quaternion classes
- quat + quat
- quat - quat
- quat * float/int
- quat * vec
- quat * quat
@note: You can access a quaternion object like a sequence
- x = quat[0]
@attention: Quaternion data can be wrapped or non-wrapped. When a object is wrapped it
means that the object will give you direct access to the data inside of blender. Modification
of this object will directly change the data inside of blender. To copy a wrapped object
you need to use the object's constructor. If you copy and object by assignment you will not get
a second copy but a second reference to the same data. Only certain functions will return
wrapped data. This will be indicated in the method description.
"""
def __init__(list, angle = None):
"""
Create a new quaternion object from initialized values.
Example::
quat = Quaternion(1,2,3,4)
quat = Quaternion(axis, angle)
quat = Quaternion()
quat = Quaternion(180, list)
@type list: PyList of int/float
@param list: A 3d or 4d list to initialize quaternion.
4d if intializing [w,x,y,z], 3d if used as an axis of rotation.
@type angle: float (optional)
@param angle: An arbitrary rotation amount around 'list'.
List is used as an axis of rotation in this case.
@rtype: New quaternion object.
@return: It depends wheter a parameter was passed:
- (list/angle): Quaternion object initialized with the given values;
- (): An identity 4 dimensional quaternion.
"""
class Matrix:
"""
The Matrix Object
=================
@note: Math can be performed on Matrix classes
- mat + mat
- mat - mat
- mat * float/int
- mat * vec
- mat * mat
@note: Comparison operators can be done:
- ==, != test numeric values within epsilon
@note: You can access a quaternion object like a 2d sequence
- x = matrix[0][1]
- vector = matrix[2]
@attention: Quaternion data can be wrapped or non-wrapped. When a object is wrapped it
means that the object will give you direct access to the data inside of blender. Modification
of this object will directly change the data inside of blender. To copy a wrapped object
you need to use the object's constructor. If you copy and object by assignment you will not get
a second copy but a second reference to the same data. Only certain functions will return
wrapped data. This will be indicated in the method description.
"""
def __init__(list1 = None, list2 = None, list3 = None, list4 = None):
"""
Create a new matrix object from initialized values.
Example::
matrix = Matrix([1,1,1],[0,1,0],[1,0,0])
matrix = Matrix(mat)
matrix = Matrix(seq1, seq2, vector)
@type list1: PyList of int/float
@param list1: A 2d,3d or 4d list.
@type list2: PyList of int/float
@param list2: A 2d,3d or 4d list.
@type list3: PyList of int/float
@param list3: A 2d,3d or 4d list.
@type list4: PyList of int/float
@param list4: A 2d,3d or 4d list.
@rtype: New matrix object.
@return: It depends wheter a parameter was passed:
- (list1, etc.): Matrix object initialized with the given values;
- (): An empty 3 dimensional matrix.
"""

View File

@@ -0,0 +1,45 @@
# Testing the BGL module
import Blender
from Blender.BGL import *
from Blender import Draw
R = G = B = 0
A = 1
instructions = "Hold mouse buttons to change the background color."
quitting = " Press ESC or q to quit."
def show_win():
glClearColor(R,G,B,A) # define color used to clear buffers
glClear(GL_COLOR_BUFFER_BIT) # use it to clear the color buffer
glColor3f(1,1,1) # change default color
glRasterPos2i(50,100) # move cursor to x = 50, y = 100
Draw.Text("Testing BGL + Draw") # draw this text there
glRasterPos2i(350,20) # move cursor again
Draw.Text(instructions + quitting) # draw another msg
glBegin(GL_LINE_LOOP) # begin a vertex-data list
glVertex2i(46,92)
glVertex2i(120,92)
glVertex2i(120,115)
glVertex2i(46,115)
glEnd() # close this list
glColor3f(0.35,0.18,0.92) # change default color again
glBegin(GL_POLYGON) # another list, for a polygon
glVertex2i(315, 292)
glVertex2i(412, 200)
glVertex2i(264, 256)
glEnd()
Draw.Redraw(1) # make changes visible.
def ev(evt, val): # this is a callback for Draw.Register()
global R,G,B,A # it handles input events
if evt == Draw.ESCKEY or evt == Draw.QKEY:
Draw.Exit() # this quits the script
elif evt == Draw.LEFTMOUSE: R = 1 - R
elif evt == Draw.MIDDLEMOUSE: G = 1 - G
elif evt == Draw.RIGHTMOUSE: B = 1 - B
else:
Draw.Register(show_win, ev, None)
Draw.Register(show_win, ev, None) # start the main loop

View File

@@ -0,0 +1,29 @@
import bpy
# print all objects
for obj in bpy.data.objects:
print(obj.name)
# print all scene names in a list
print(bpy.data.scenes.keys())
# remove mesh Cube
if "Cube" in bpy.data.meshes:
mesh = bpy.data.meshes["Cube"]
print("removing mesh", mesh)
bpy.data.meshes.unlink(mesh)
# write images into a file next to the blend
import os
file = open(os.path.splitext(bpy.data.filepath)[0] + ".txt", 'w')
for image in bpy.data.images:
file.write("%s %dx%d\n" % (image.filepath, image.size[0], image.size[1]))
file.close()

View File

@@ -0,0 +1,3 @@
import mathutils
# todo

View File

@@ -0,0 +1,3 @@
import mathutils
# todo

View File

@@ -0,0 +1,3 @@
import mathutils
# todo

View File

@@ -0,0 +1,55 @@
import mathutils
# zero length vector
vec = mathutils.Vector((0, 0, 1))
# unit length vector
vec_a = vec.copy().normalize()
vec_b = mathutils.Vector((0, 1, 2))
vec2d = mathutils.Vector((1, 2))
vec3d = mathutils.Vector((1, 0, 0))
vec4d = vec_a.copy().resize4D()
# other mathutuls types
quat = mathutils.Quaternion()
matrix = mathutils.Matrix()
# Comparison operators can be done on Vector classes:
# greater and less then test vector length.
vec_a > vec_b
vec_a >= vec_b
vec_a < vec_b
vec_a <= vec_b
# ==, != test vector values e.g. 1,2,3 != 3,2,1 even if they are the same length
vec_a == vec_b
vec_a != vec_b
# Math can be performed on Vector classes
vec_a + vec_b
vec_a - vec_b
vec_a * vec_b
vec_a * 10.0
vec_a * matrix
vec_a * vec_b
vec_a * quat
-vec_a
# You can access a vector object like a sequence
x = vec_a[0]
len(vec)
vec_a[:] = vec_b
vec2d[:] = vec3d[:2]
# Vectors support 'swizzle' operations
# See http://en.wikipedia.org/wiki/Swizzling_(computer_graphics)
vec.xyz = vec.zyx
vec.xy = vec4d.zw
vec.xyz = vec4d.wzz
vec4d.wxyz = vec.yxyx

View File

@@ -0,0 +1,18 @@
import mathutils
from math import radians
vec = mathutils.Vector((1.0, 2.0, 3.0))
mat_rot = mathutils.Matrix.Rotation(radians(90), 4, 'X')
mat_trans = mathutils.Matrix.Translation(vec)
mat = mat_trans * mat_rot
mat.invert()
mat3 = mat.rotation_part()
quat1 = mat.to_quat()
quat2 = mat3.to_quat()
angle = quat1.difference(quat2)
print(angle)

View File

@@ -0,0 +1,250 @@
Game Engine bge.events module
=============================
*****
Intro
*****
This module holds key constants for the SCA_KeyboardSensor.
.. module:: bge.events
.. code-block:: python
# Set a connected keyboard sensor to accept F1
import bge
co = bge.logic.getCurrentController()
# 'Keyboard' is a keyboard sensor
sensor = co.sensors["Keyboard"]
sensor.key = bge.events.F1KEY
.. code-block:: python
# Do the all keys thing
import bge
co = bge.logic.getCurrentController()
# 'Keyboard' is a keyboard sensor
sensor = co.sensors["Keyboard"]
for key,status in sensor.events:
# key[0] == bge.events.keycode, key[1] = status
if status == bge.logic.KX_INPUT_JUST_ACTIVATED:
if key == bge.events.WKEY:
# Activate Forward!
if key == bge.events.SKEY:
# Activate Backward!
if key == bge.events.AKEY:
# Activate Left!
if key == bge.events.DKEY:
# Activate Right!
.. code-block:: python
# The all keys thing without a keyboard sensor (but you will
# need an always sensor with pulse mode on)
import bge
# Just shortening names here
keyboard = bge.logic.keyboard
JUST_ACTIVATED = bge.logic.KX_INPUT_JUST_ACTIVATED
if keyboard.events[bge.events.WKEY] == JUST_ACTIVATED:
print("Activate Forward!")
if keyboard.events[bge.events.SKEY] == JUST_ACTIVATED:
print("Activate Backward!")
if keyboard.events[bge.events.AKEY] == JUST_ACTIVATED:
print("Activate Left!")
if keyboard.events[bge.events.DKEY] == JUST_ACTIVATED:
print("Activate Right!")
*********
Functions
*********
.. function:: EventToString(event)
Return the string name of a key event. Will raise a ValueError error if its invalid.
:arg event: key event from bge.keys or the keyboard sensor.
:type event: int
:rtype: string
.. function:: EventToCharacter(event, shift)
Return the string name of a key event. Returns an empty string if the event cant be represented as a character.
:type event: int
:arg event: key event from :mod:`bge.keys` or the keyboard sensor.
:type shift: bool
:arg shift: set to true if shift is held.
:rtype: string
****************
Keys (Constants)
****************
.. _mouse-keys:
==========
Mouse Keys
==========
.. data:: LEFTMOUSE
.. data:: MIDDLEMOUSE
.. data:: RIGHTMOUSE
.. data:: WHEELUPMOUSE
.. data:: WHEELDOWNMOUSE
.. data:: MOUSEX
.. data:: MOUSEY
.. _keyboard-keys:
=============
Keyboard Keys
=============
-------------
Alphabet keys
-------------
.. data:: AKEY
.. data:: BKEY
.. data:: CKEY
.. data:: DKEY
.. data:: EKEY
.. data:: FKEY
.. data:: GKEY
.. data:: HKEY
.. data:: IKEY
.. data:: JKEY
.. data:: KKEY
.. data:: LKEY
.. data:: MKEY
.. data:: NKEY
.. data:: OKEY
.. data:: PKEY
.. data:: QKEY
.. data:: RKEY
.. data:: SKEY
.. data:: TKEY
.. data:: UKEY
.. data:: VKEY
.. data:: WKEY
.. data:: XKEY
.. data:: YKEY
.. data:: ZKEY
-----------
Number keys
-----------
.. data:: ZEROKEY
.. data:: ONEKEY
.. data:: TWOKEY
.. data:: THREEKEY
.. data:: FOURKEY
.. data:: FIVEKEY
.. data:: SIXKEY
.. data:: SEVENKEY
.. data:: EIGHTKEY
.. data:: NINEKEY
--------------
Modifiers Keys
--------------
.. data:: CAPSLOCKKEY
.. data:: LEFTCTRLKEY
.. data:: LEFTALTKEY
.. data:: RIGHTALTKEY
.. data:: RIGHTCTRLKEY
.. data:: RIGHTSHIFTKEY
.. data:: LEFTSHIFTKEY
----------
Arrow Keys
----------
.. data:: LEFTARROWKEY
.. data:: DOWNARROWKEY
.. data:: RIGHTARROWKEY
.. data:: UPARROWKEY
--------------
Numberpad Keys
--------------
.. data:: PAD0
.. data:: PAD1
.. data:: PAD2
.. data:: PAD3
.. data:: PAD4
.. data:: PAD5
.. data:: PAD6
.. data:: PAD7
.. data:: PAD8
.. data:: PAD9
.. data:: PADPERIOD
.. data:: PADSLASHKEY
.. data:: PADASTERKEY
.. data:: PADMINUS
.. data:: PADENTER
.. data:: PADPLUSKEY
-------------
Function Keys
-------------
.. data:: F1KEY
.. data:: F2KEY
.. data:: F3KEY
.. data:: F4KEY
.. data:: F5KEY
.. data:: F6KEY
.. data:: F7KEY
.. data:: F8KEY
.. data:: F9KEY
.. data:: F10KEY
.. data:: F11KEY
.. data:: F12KEY
.. data:: F13KEY
.. data:: F14KEY
.. data:: F15KEY
.. data:: F16KEY
.. data:: F17KEY
.. data:: F18KEY
.. data:: F19KEY
----------
Other Keys
----------
.. data:: ACCENTGRAVEKEY
.. data:: BACKSLASHKEY
.. data:: BACKSPACEKEY
.. data:: COMMAKEY
.. data:: DELKEY
.. data:: ENDKEY
.. data:: EQUALKEY
.. data:: ESCKEY
.. data:: HOMEKEY
.. data:: INSERTKEY
.. data:: LEFTBRACKETKEY
.. data:: LINEFEEDKEY
.. data:: MINUSKEY
.. data:: PAGEDOWNKEY
.. data:: PAGEUPKEY
.. data:: PAUSEKEY
.. data:: PERIODKEY
.. data:: QUOTEKEY
.. data:: RIGHTBRACKETKEY
.. data:: RETKEY (Deprecated: use bge.events.ENTERKEY)
.. data:: ENTERKEY
.. data:: SEMICOLONKEY
.. data:: SLASHKEY
.. data:: SPACEKEY
.. data:: TABKEY

View File

@@ -0,0 +1,932 @@
Game Engine bge.logic Module
============================
*****
Intro
*****
Module to access logic functions, imported automatically into the python controllers namespace.
.. module:: bge.logic
.. code-block:: python
# To get the controller thats running this python script:
cont = bge.logic.getCurrentController() # bge.logic is automatically imported
# To get the game object this controller is on:
obj = cont.owner
:class:`~bge.types.KX_GameObject` and :class:`~bge.types.KX_Camera` or :class:`bge.types.~KX_LightObject` methods are available depending on the type of object
.. code-block:: python
# To get a sensor linked to this controller.
# "sensorname" is the name of the sensor as defined in the Blender interface.
# +---------------------+ +--------+
# | Sensor "sensorname" +--+ Python +
# +---------------------+ +--------+
sens = cont.sensors["sensorname"]
# To get a sequence of all sensors:
sensors = co.sensors
See the sensor's reference for available methods:
.. hlist::
:columns: 3
* :class:`~bge.types.KX_MouseFocusSensor`
* :class:`~bge.types.KX_NearSensor`
* :class:`~bge.types.KX_NetworkMessageSensor`
* :class:`~bge.types.KX_RadarSensor`
* :class:`~bge.types.KX_RaySensor`
* :class:`~bge.types.KX_TouchSensor`
* :class:`~bge.types.SCA_DelaySensor`
* :class:`~bge.types.SCA_JoystickSensor`
* :class:`~bge.types.SCA_KeyboardSensor`
* :class:`~bge.types.SCA_MouseSensor`
* :class:`~bge.types.SCA_PropertySensor`
* :class:`~bge.types.SCA_RandomSensor`
You can also access actuators linked to the controller
.. code-block:: python
# To get an actuator attached to the controller:
# +--------+ +-------------------------+
# + Python +--+ Actuator "actuatorname" |
# +--------+ +-------------------------+
actuator = co.actuators["actuatorname"]
# Activate an actuator
controller.activate(actuator)
See the actuator's reference for available methods
.. hlist::
:columns: 3
* :class:`~bge.types.BL_ActionActuator`
* :class:`~bge.types.BL_ShapeActionActuator`
* :class:`~bge.types.KX_CameraActuator`
* :class:`~bge.types.KX_ConstraintActuator`
* :class:`~bge.types.KX_GameActuator`
* :class:`~bge.types.KX_IpoActuator`
* :class:`~bge.types.KX_NetworkMessageActuator`
* :class:`~bge.types.KX_ObjectActuator`
* :class:`~bge.types.KX_ParentActuator`
* :class:`~bge.types.KX_SCA_AddObjectActuator`
* :class:`~bge.types.KX_SCA_DynamicActuator`
* :class:`~bge.types.KX_SCA_EndObjectActuator`
* :class:`~bge.types.KX_SCA_ReplaceMeshActuator`
* :class:`~bge.types.KX_SceneActuator`
* :class:`~bge.types.KX_SoundActuator`
* :class:`~bge.types.KX_StateActuator`
* :class:`~bge.types.KX_TrackToActuator`
* :class:`~bge.types.KX_VisibilityActuator`
* :class:`~bge.types.SCA_2DFilterActuator`
* :class:`~bge.types.SCA_PropertyActuator`
* :class:`~bge.types.SCA_RandomActuator`
Most logic brick's methods are accessors for the properties available in the logic buttons.
Consult the logic bricks documentation for more information on how each logic brick works.
There are also methods to access the current :class:`bge.types.KX_Scene`
.. code-block:: python
# Get the current scene
scene = bge.logic.getCurrentScene()
# Get the current camera
cam = scene.active_camera
Matricies as used by the game engine are **row major**
``matrix[row][col] = float``
:class:`bge.types.KX_Camera` has some examples using matricies.
*********
Variables
*********
.. data:: globalDict
A dictionary that is saved between loading blend files so you can use it to store inventory and other variables you want to store between scenes and blend files.
It can also be written to a file and loaded later on with the game load/save actuators.
.. note:: only python built in types such as int/string/bool/float/tuples/lists can be saved, GameObjects, Actuators etc will not work as expected.
.. data:: keyboard
The current keyboard wrapped in an :class:`~bge.types.SCA_PythonKeyboard` object.
.. data:: mouse
The current mouse wrapped in an :class:`~bge.types.SCA_PythonMouse` object.
*****************
General functions
*****************
.. function:: getCurrentController()
Gets the Python controller associated with this Python script.
:rtype: :class:`bge.types.SCA_PythonController`
.. function:: getCurrentScene()
Gets the current Scene.
:rtype: :class:`bge.types.KX_Scene`
.. function:: getSceneList()
Gets a list of the current scenes loaded in the game engine.
:rtype: list of :class:`bge.types.KX_Scene`
.. note:: Scenes in your blend file that have not been converted wont be in this list. This list will only contain scenes such as overlays scenes.
.. function:: loadGlobalDict()
Loads bge.logic.globalDict from a file.
.. function:: saveGlobalDict()
Saves bge.logic.globalDict to a file.
.. function:: startGame(blend)
Loads the blend file.
:arg blend: The name of the blend file
:type blend: string
.. function:: endGame()
Ends the current game.
.. function:: restartGame()
Restarts the current game by reloading the .blend file (the last saved version, not what is currently running).
.. function:: LibLoad(blend, type, data)
Converts the all of the datablocks of the given type from the given blend.
:arg blend: The path to the blend file (or the name to use for the library if data is supplied)
:type blend: string
:arg type: The datablock type (currently only "Action", "Mesh" and "Scene" are supported)
:type type: string
:arg data: Binary data from a blend file (optional)
:type data: bytes
.. function:: LibNew(name, type, data)
Uses existing datablock data and loads in as a new library.
:arg name: A unique library name used for removal later
:type name: string
:arg type: The datablock type (currently only "Mesh" is supported)
:type type: string
:arg data: A list of names of the datablocks to load
:type data: list of strings
.. function:: LibFree(name)
Frees a library, removing all objects and meshes from the currently active scenes.
:arg name: The name of the library to free (the name used in LibNew)
:type name: string
.. function:: addScene(name, overlay=1)
Loads a scene into the game engine.
:arg name: The name of the scene
:type name: string
:arg overlay: Overlay or underlay (optional)
:type overlay: integer
.. function:: sendMessage(subject, body="", to="", message_from="")
Sends a message to sensors in any active scene.
:arg subject: The subject of the message
:type subject: string
:arg body: The body of the message (optional)
:type body: string
:arg to: The name of the object to send the message to (optional)
:type to: string
:arg message_from: The name of the object that the message is coming from (optional)
:type message_from: string
.. function:: setGravity(gravity)
Sets the world gravity.
:type gravity: list [fx, fy, fz]
.. function:: getSpectrum()
Returns a 512 point list from the sound card.
This only works if the fmod sound driver is being used.
:rtype: list [float], len(getSpectrum()) == 512
.. function:: stopDSP()
Stops the sound driver using DSP effects.
Only the fmod sound driver supports this.
DSP can be computationally expensive.
.. function:: getMaxLogicFrame()
Gets the maximum number of logic frames per render frame.
:return: The maximum number of logic frames per render frame
:rtype: integer
.. function:: setMaxLogicFrame(maxlogic)
Sets the maximum number of logic frames that are executed per render frame.
This does not affect the physic system that still runs at full frame rate.
:arg maxlogic: The new maximum number of logic frames per render frame. Valid values: 1..5
:type maxlogic: integer
.. function:: getMaxPhysicsFrame()
Gets the maximum number of physics frames per render frame.
:return: The maximum number of physics frames per render frame
:rtype: integer
.. function:: setMaxPhysicsFrame(maxphysics)
Sets the maximum number of physics timestep that are executed per render frame.
Higher value allows physics to keep up with realtime even if graphics slows down the game.
Physics timestep is fixed and equal to 1/tickrate (see setLogicTicRate)
maxphysics/ticrate is the maximum delay of the renderer that physics can compensate.
:arg maxphysics: The new maximum number of physics timestep per render frame. Valid values: 1..5.
:type maxphysics: integer
.. function:: getLogicTicRate()
Gets the logic update frequency.
:return: The logic frequency in Hz
:rtype: float
.. function:: setLogicTicRate(ticrate)
Sets the logic update frequency.
The logic update frequency is the number of times logic bricks are executed every second.
The default is 60 Hz.
:arg ticrate: The new logic update frequency (in Hz).
:type ticrate: float
.. function:: getPhysicsTicRate()
Gets the physics update frequency
:return: The physics update frequency in Hz
:rtype: float
.. warning: Not implimented yet
.. function:: setPhysicsTicRate(ticrate)
Sets the physics update frequency
The physics update frequency is the number of times the physics system is executed every second.
The default is 60 Hz.
:arg ticrate: The new update frequency (in Hz).
:type ticrate: float
.. warning: Not implimented yet
*****************
Utility functions
*****************
.. function:: expandPath(path)
Converts a blender internal path into a proper file system path.
Use / as directory separator in path
You can use '//' at the start of the string to define a relative path;
Blender replaces that string by the directory of the startup .blend or runtime file
to make a full path name (doesn't change during the game, even if you load other .blend).
The function also converts the directory separator to the local file system format.
:arg path: The path string to be converted/expanded.
:type path: string
:return: The converted string
:rtype: string
.. function:: getAverageFrameRate()
Gets the estimated average framerate
:return: The estimed average framerate in frames per second
:rtype: float
.. function:: getBlendFileList(path = "//")
Returns a list of blend files in the same directory as the open blend file, or from using the option argument.
:arg path: Optional directory argument, will be expanded (like expandPath) into the full path.
:type path: string
:return: A list of filenames, with no directory prefix
:rtype: list
.. function:: getRandomFloat()
Returns a random floating point value in the range [0 - 1)
.. function:: PrintGLInfo()
Prints GL Extension Info into the console
*********
Constants
*********
.. data:: KX_TRUE
True value used by some modules.
.. data:: KX_FALSE
False value used by some modules.
=======
Sensors
=======
.. _sensor-status:
-------------
Sensor Status
-------------
.. data:: KX_SENSOR_INACTIVE
.. data:: KX_SENSOR_JUST_ACTIVATED
.. data:: KX_SENSOR_ACTIVE
.. data:: KX_SENSOR_JUST_DEACTIVATED
.. _logic-property-sensor:
---------------
Property Sensor
---------------
.. data:: KX_PROPSENSOR_EQUAL
Activate when the property is equal to the sensor value.
:value: 1
.. data:: KX_PROPSENSOR_NOTEQUAL
Activate when the property is not equal to the sensor value.
:value: 2
.. data:: KX_PROPSENSOR_INTERVAL
Activate when the property is between the specified limits.
:value: 3
.. data:: KX_PROPSENSOR_CHANGED
Activate when the property changes
:value: 4
.. data:: KX_PROPSENSOR_EXPRESSION
Activate when the expression matches
:value: 5
------------
Radar Sensor
------------
See :class:`bge.types.KX_RadarSensor`
.. data:: KX_RADAR_AXIS_POS_X
.. data:: KX_RADAR_AXIS_POS_Y
.. data:: KX_RADAR_AXIS_POS_Z
.. data:: KX_RADAR_AXIS_NEG_X
.. data:: KX_RADAR_AXIS_NEG_Y
.. data:: KX_RADAR_AXIS_NEG_Z
----------
Ray Sensor
----------
See :class:`bge.types.KX_RaySensor`
.. data:: KX_RAY_AXIS_POS_X
.. data:: KX_RAY_AXIS_POS_Y
.. data:: KX_RAY_AXIS_POS_Z
.. data:: KX_RAY_AXIS_NEG_X
.. data:: KX_RAY_AXIS_NEG_Y
.. data:: KX_RAY_AXIS_NEG_Z
=========
Actuators
=========
.. _action-actuator:
---------------
Action Actuator
---------------
See :class:`bge.types.BL_ActionActuator`
.. data:: KX_ACTIONACT_PLAY
.. data:: KX_ACTIONACT_FLIPPER
.. data:: KX_ACTIONACT_LOOPSTOP
.. data:: KX_ACTIONACT_LOOPEND
.. data:: KX_ACTIONACT_PROPERTY
-------------------
Constraint Actuator
-------------------
.. _constraint-actuator-option:
See :class:`bge.types.KX_ConstraintActuator.option`
* Applicable to Distance constraint:
.. data:: KX_ACT_CONSTRAINT_NORMAL
Activate alignment to surface
.. data:: KX_ACT_CONSTRAINT_DISTANCE
Activate distance control
.. data:: KX_ACT_CONSTRAINT_LOCAL
Direction of the ray is along the local axis
* Applicable to Force field constraint:
.. data:: KX_ACT_CONSTRAINT_DOROTFH
Force field act on rotation as well
* Applicable to both:
.. data:: KX_ACT_CONSTRAINT_MATERIAL
Detect material rather than property
.. data:: KX_ACT_CONSTRAINT_PERMANENT
No deactivation if ray does not hit target
.. _constraint-actuator-limit:
See :class:`bge.types.KX_ConstraintActuator.limit`
.. data:: KX_CONSTRAINTACT_LOCX
Limit X coord.
.. data:: KX_CONSTRAINTACT_LOCY
Limit Y coord
.. data:: KX_CONSTRAINTACT_LOCZ
Limit Z coord
.. data:: KX_CONSTRAINTACT_ROTX
Limit X rotation
.. data:: KX_CONSTRAINTACT_ROTY
Limit Y rotation
.. data:: KX_CONSTRAINTACT_ROTZ
Limit Z rotation
.. data:: KX_CONSTRAINTACT_DIRNX
Set distance along negative X axis
.. data:: KX_CONSTRAINTACT_DIRNY
Set distance along negative Y axis
.. data:: KX_CONSTRAINTACT_DIRNZ
Set distance along negative Z axis
.. data:: KX_CONSTRAINTACT_DIRPX
Set distance along positive X axis
.. data:: KX_CONSTRAINTACT_DIRPY
Set distance along positive Y axis
.. data:: KX_CONSTRAINTACT_DIRPZ
Set distance along positive Z axis
.. data:: KX_CONSTRAINTACT_ORIX
Set orientation of X axis
.. data:: KX_CONSTRAINTACT_ORIY
Set orientation of Y axis
.. data:: KX_CONSTRAINTACT_ORIZ
Set orientation of Z axis
.. data:: KX_ACT_CONSTRAINT_FHNX
Set force field along negative X axis
.. data:: KX_ACT_CONSTRAINT_FHNY
Set force field along negative Y axis
.. data:: KX_ACT_CONSTRAINT_FHNZ
Set force field along negative Z axis
.. data:: KX_ACT_CONSTRAINT_FHPX
Set force field along positive X axis
.. data:: KX_ACT_CONSTRAINT_FHPY
Set force field along positive Y axis
.. data:: KX_ACT_CONSTRAINT_FHPZ
Set force field along positive Z axis
----------------
Dynamic Actuator
----------------
See :class:`bge.types.KX_SCA_DynamicActuator`
.. data:: KX_DYN_RESTORE_DYNAMICS
.. data:: KX_DYN_DISABLE_DYNAMICS
.. data:: KX_DYN_ENABLE_RIGID_BODY
.. data:: KX_DYN_DISABLE_RIGID_BODY
.. data:: KX_DYN_SET_MASS
.. _game-actuator:
-------------
Game Actuator
-------------
See :class:`bge.types.KX_GameActuator`
.. data:: KX_GAME_LOAD
.. data:: KX_GAME_START
.. data:: KX_GAME_RESTART
.. data:: KX_GAME_QUIT
.. data:: KX_GAME_SAVECFG
.. data:: KX_GAME_LOADCFG
.. _ipo-actuator:
------------
IPO Actuator
------------
See :class:`bge.types.KX_IpoActuator`
.. data:: KX_IPOACT_PLAY
.. data:: KX_IPOACT_PINGPONG
.. data:: KX_IPOACT_FLIPPER
.. data:: KX_IPOACT_LOOPSTOP
.. data:: KX_IPOACT_LOOPEND
.. data:: KX_IPOACT_FROM_PROP
---------------
Parent Actuator
---------------
.. data:: KX_PARENT_REMOVE
.. data:: KX_PARENT_SET
.. _logic-random-distributions:
--------------------
Random Distributions
--------------------
See :class:`bge.types.SCA_RandomActuator`
.. data:: KX_RANDOMACT_BOOL_CONST
.. data:: KX_RANDOMACT_BOOL_UNIFORM
.. data:: KX_RANDOMACT_BOOL_BERNOUILLI
.. data:: KX_RANDOMACT_INT_CONST
.. data:: KX_RANDOMACT_INT_UNIFORM
.. data:: KX_RANDOMACT_INT_POISSON
.. data:: KX_RANDOMACT_FLOAT_CONST
.. data:: KX_RANDOMACT_FLOAT_UNIFORM
.. data:: KX_RANDOMACT_FLOAT_NORMAL
.. data:: KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL
--------------
Scene Actuator
--------------
See :class:`bge.types.KX_SceneActuator`
.. data:: KX_SCENE_RESTART
.. data:: KX_SCENE_SET_SCENE
.. data:: KX_SCENE_SET_CAMERA
.. data:: KX_SCENE_ADD_FRONT_SCENE
.. data:: KX_SCENE_ADD_BACK_SCENE
.. data:: KX_SCENE_REMOVE_SCENE
.. data:: KX_SCENE_SUSPEND
.. data:: KX_SCENE_RESUME
.. _shape-action-actuator:
---------------------
Shape Action Actuator
---------------------
See :class:`bge.types.BL_ActionActuator`
.. data:: KX_ACTIONACT_PLAY
.. data:: KX_ACTIONACT_FLIPPER
.. data:: KX_ACTIONACT_LOOPSTOP
.. data:: KX_ACTIONACT_LOOPEND
.. data:: KX_ACTIONACT_PROPERTY
.. _logic-sound-actuator:
--------------
Sound Actuator
--------------
See :class:`bge.types.KX_SoundActuator`
.. data:: KX_SOUNDACT_PLAYSTOP
:value: 1
.. data:: KX_SOUNDACT_PLAYEND
:value: 2
.. data:: KX_SOUNDACT_LOOPSTOP
:value: 3
.. data:: KX_SOUNDACT_LOOPEND
:value: 4
.. data:: KX_SOUNDACT_LOOPBIDIRECTIONAL
:value: 5
.. data:: KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP
:value: 6
=======
Various
=======
.. _input-status:
------------
Input Status
------------
See :class:`bge.types.SCA_PythonKeyboard`, :class:`bge.types.SCA_PythonMouse`, :class:`bge.types.SCA_MouseSensor`, :class:`bge.types.SCA_KeyboardSensor`
.. data:: KX_INPUT_NONE
.. data:: KX_INPUT_JUST_ACTIVATED
.. data:: KX_INPUT_ACTIVE
.. data:: KX_INPUT_JUST_RELEASED
-------------
Mouse Buttons
-------------
See :class:`bge.types.SCA_MouseSensor`
.. data:: KX_MOUSE_BUT_LEFT
.. data:: KX_MOUSE_BUT_MIDDLE
.. data:: KX_MOUSE_BUT_RIGHT
------
States
------
See :class:`bge.types.KX_StateActuator`
.. data:: KX_STATE1
.. data:: KX_STATE2
.. data:: KX_STATE3
.. data:: KX_STATE4
.. data:: KX_STATE5
.. data:: KX_STATE6
.. data:: KX_STATE7
.. data:: KX_STATE8
.. data:: KX_STATE9
.. data:: KX_STATE10
.. data:: KX_STATE11
.. data:: KX_STATE12
.. data:: KX_STATE13
.. data:: KX_STATE14
.. data:: KX_STATE15
.. data:: KX_STATE16
.. data:: KX_STATE17
.. data:: KX_STATE18
.. data:: KX_STATE19
.. data:: KX_STATE20
.. data:: KX_STATE21
.. data:: KX_STATE22
.. data:: KX_STATE23
.. data:: KX_STATE24
.. data:: KX_STATE25
.. data:: KX_STATE26
.. data:: KX_STATE27
.. data:: KX_STATE28
.. data:: KX_STATE29
.. data:: KX_STATE30
.. _state-actuator-operation:
See :class:`bge.types.KX_StateActuator.operation`
.. data:: KX_STATE_OP_CLR
Substract bits to state mask
:value: 0
.. data:: KX_STATE_OP_CPY
Copy state mask
:value: 1
.. data:: KX_STATE_OP_NEG
Invert bits to state mask
:value: 2
.. data:: KX_STATE_OP_SET
Add bits to state mask
:value: 3
.. _Two-D-FilterActuator-mode:
---------
2D Filter
---------
.. data:: RAS_2DFILTER_BLUR
:value: 2
.. data:: RAS_2DFILTER_CUSTOMFILTER
Customer filter, the code code is set via shaderText property.
:value: 12
.. data:: RAS_2DFILTER_DILATION
:value: 4
.. data:: RAS_2DFILTER_DISABLED
Disable the filter that is currently active
:value: -1
.. data:: RAS_2DFILTER_ENABLED
Enable the filter that was previously disabled
:value: -2
.. data:: RAS_2DFILTER_EROSION
:value: 5
.. data:: RAS_2DFILTER_GRAYSCALE
:value: 9
.. data:: RAS_2DFILTER_INVERT
:value: 11
.. data:: RAS_2DFILTER_LAPLACIAN
:value: 6
.. data:: RAS_2DFILTER_MOTIONBLUR
Create and enable preset filters
:value: 1
.. data:: RAS_2DFILTER_NOFILTER
Disable and destroy the filter that is currently active
:value: 0
.. data:: RAS_2DFILTER_PREWITT
:value: 8
.. data:: RAS_2DFILTER_SEPIA
:value: 10
.. data:: RAS_2DFILTER_SHARPEN
:value: 3
.. data:: RAS_2DFILTER_SOBEL
:value: 7
------
Shader
------
.. data:: VIEWMATRIX
.. data:: VIEWMATRIX_INVERSE
.. data:: VIEWMATRIX_INVERSETRANSPOSE
.. data:: VIEWMATRIX_TRANSPOSE
.. data:: MODELMATRIX
.. data:: MODELMATRIX_INVERSE
.. data:: MODELMATRIX_INVERSETRANSPOSE
.. data:: MODELMATRIX_TRANSPOSE
.. data:: MODELVIEWMATRIX
.. data:: MODELVIEWMATRIX_INVERSE
.. data:: MODELVIEWMATRIX_INVERSETRANSPOSE
.. data:: MODELVIEWMATRIX_TRANSPOSE
.. data:: CAM_POS
Current camera position
.. data:: CONSTANT_TIMER
User a timer for the uniform value.
.. data:: SHD_TANGENT
----------------
Blender Material
----------------
.. data:: BL_DST_ALPHA
.. data:: BL_DST_COLOR
.. data:: BL_ONE
.. data:: BL_ONE_MINUS_DST_ALPHA
.. data:: BL_ONE_MINUS_DST_COLOR
.. data:: BL_ONE_MINUS_SRC_ALPHA
.. data:: BL_ONE_MINUS_SRC_COLOR
.. data:: BL_SRC_ALPHA
.. data:: BL_SRC_ALPHA_SATURATE
.. data:: BL_SRC_COLOR
.. data:: BL_ZERO

View File

@@ -0,0 +1,242 @@
Game Engine bge.render Module
=============================
*****
Intro
*****
.. module:: bge.render
.. code-block:: python
# Example Uses an L{SCA_MouseSensor}, and two L{KX_ObjectActuator}s to implement MouseLook::
# To use a mouse movement sensor "Mouse" and a
# motion actuator to mouse look:
import bge.render
import bge.logic
# SCALE sets the speed of motion
SCALE=[1, 0.5]
co = bge.logic.getCurrentController()
obj = co.getOwner()
mouse = co.getSensor("Mouse")
lmotion = co.getActuator("LMove")
wmotion = co.getActuator("WMove")
# Transform the mouse coordinates to see how far the mouse has moved.
def mousePos():
x = (bge.render.getWindowWidth()/2 - mouse.getXPosition())*SCALE[0]
y = (bge.render.getWindowHeight()/2 - mouse.getYPosition())*SCALE[1]
return (x, y)
pos = mousePos()
# Set the amount of motion: X is applied in world coordinates...
lmotion.setTorque(0.0, 0.0, pos[0], False)
# ...Y is applied in local coordinates
wmotion.setTorque(-pos[1], 0.0, 0.0, True)
# Activate both actuators
bge.logic.addActiveActuator(lmotion, True)
bge.logic.addActiveActuator(wmotion, True)
# Centre the mouse
bge.render.setMousePosition(bge.render.getWindowWidth()/2, bge.render.getWindowHeight()/2)
*********
Constants
*********
.. data:: KX_TEXFACE_MATERIAL
Materials as defined by the texture face settings.
.. data:: KX_BLENDER_MULTITEX_MATERIAL
Materials approximating blender materials with multitexturing.
.. data:: KX_BLENDER_GLSL_MATERIAL
Materials approximating blender materials with GLSL.
*********
Functions
*********
.. function:: getWindowWidth()
Gets the width of the window (in pixels)
:rtype: integer
.. function:: getWindowHeight()
Gets the height of the window (in pixels)
:rtype: integer
.. function:: makeScreenshot(filename)
Writes a screenshot to the given filename.
If filename starts with // the image will be saved relative to the current directory.
If the filename contains # it will be replaced with the frame number.
The standalone player saves .png files. It does not support colour space conversion
or gamma correction.
When run from Blender, makeScreenshot supports Iris, IrisZ, TGA, Raw TGA, PNG, HamX, and Jpeg.
Gamma, Colourspace conversion and Jpeg compression are taken from the Render settings panels.
:type filename: string
.. function:: enableVisibility(visible)
Doesn't really do anything...
.. function:: showMouse(visible)
Enables or disables the operating system mouse cursor.
:type visible: boolean
.. function:: setMousePosition(x, y)
Sets the mouse cursor position.
:type x: integer
:type y: integer
.. function:: setBackgroundColor(rgba)
Sets the window background colour.
:type rgba: list [r, g, b, a]
.. function:: setMistColor(rgb)
Sets the mist colour.
:type rgb: list [r, g, b]
.. function:: setAmbientColor(rgb)
Sets the color of ambient light.
:type rgb: list [r, g, b]
.. function:: setMistStart(start)
Sets the mist start value. Objects further away than start will have mist applied to them.
:type start: float
.. function:: setMistEnd(end)
Sets the mist end value. Objects further away from this will be coloured solid with
the colour set by setMistColor().
:type end: float
.. function:: disableMist()
Disables mist.
.. note:: Set any of the mist properties to enable mist.
.. function:: setEyeSeparation(eyesep)
Sets the eye separation for stereo mode. Usually Focal Length/30 provides a confortable value.
:arg eyesep: The distance between the left and right eye.
:type eyesep: float
.. function:: getEyeSeparation()
Gets the current eye separation for stereo mode.
:rtype: float
.. function:: setFocalLength(focallength)
Sets the focal length for stereo mode. It uses the current camera focal length as initial value.
:arg focallength: The focal length.
:type focallength: float
.. function:: getFocalLength()
Gets the current focal length for stereo mode.
:rtype: float
.. function:: setMaterialMode(mode)
Set the material mode to use for OpenGL rendering.
:type mode: KX_TEXFACE_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_GLSL_MATERIAL
.. note:: Changes will only affect newly created scenes.
.. function:: getMaterialMode(mode)
Get the material mode to use for OpenGL rendering.
:rtype: KX_TEXFACE_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_GLSL_MATERIAL
.. function:: setGLSLMaterialSetting(setting, enable)
Enables or disables a GLSL material setting.
:type setting: string (lights, shaders, shadows, ramps, nodes, extra_textures)
:type enable: boolean
.. function:: getGLSLMaterialSetting(setting, enable)
Get the state of a GLSL material setting.
:type setting: string (lights, shaders, shadows, ramps, nodes, extra_textures)
:rtype: boolean
.. function:: drawLine(fromVec,toVec,color)
Draw a line in the 3D scene.
:arg fromVec: the origin of the line
:type fromVec: list [x, y, z]
:arg toVec: the end of the line
:type toVec: list [x, y, z]
:arg color: the color of the line
:type color: list [r, g, b]
.. function:: enableMotionBlur(factor)
Enable the motion blur effect.
:arg factor: the ammount of motion blur to display.
:type factor: float [0.0 - 1.0]
.. function:: disableMotionBlur()
Disable the motion blur effect.

View File

@@ -0,0 +1,5227 @@
Game Engine bge.types Module
=============================
.. module:: bge.types
.. class:: PyObjectPlus
PyObjectPlus base class of most other types in the Game Engine.
.. attribute:: invalid
Test if the object has been freed by the game engine and is no longer valid.
Normally this is not a problem but when storing game engine data in the GameLogic module,
KX_Scenes or other KX_GameObjects its possible to hold a reference to invalid data.
Calling an attribute or method on an invalid object will raise a SystemError.
The invalid attribute allows testing for this case without exception handling.
:type: boolean
.. method:: isA(game_type)
Check if this is a type or a subtype game_type.
:arg game_type: the name of the type or the type its self from the :mod:`bge.types` module.
:type game_type: string or type
:return: True if this object is a type or a subtype of game_type.
:rtype: boolean
.. class:: CValue(PyObjectPlus)
This class is a basis for other classes.
.. attribute:: name
The name of this CValue derived object (read-only).
:type: string
.. class:: CPropValue(CValue)
This class has no python functions
.. class:: SCA_ILogicBrick(CValue)
Base class for all logic bricks.
.. attribute:: executePriority
This determines the order controllers are evaluated, and actuators are activated (lower priority is executed first).
:type: executePriority: int
.. attribute:: owner
The game object this logic brick is attached to (read-only).
:type: :class:`KX_GameObject` or None in exceptional cases.
.. attribute:: name
The name of this logic brick (read-only).
:type: string
.. class:: SCA_PythonKeyboard(PyObjectPlus)
The current keyboard.
.. attribute:: events
A dictionary containing the status of each keyboard event or key. (read-only).
:type: dictionary {:ref:`keycode<keyboard-keys>`::ref:`status<input-status>`, ...}
.. class:: SCA_PythonMouse(PyObjectPlus)
The current mouse.
.. attribute:: events
a dictionary containing the status of each mouse event. (read-only).
:type: dictionary {:ref:`keycode<mouse-keys>`::ref:`status<input-status>`, ...}
.. attribute:: position
The normalized x and y position of the mouse cursor.
:type: list [x, y]
.. attribute:: visible
The visibility of the mouse cursor.
:type: boolean
.. class:: SCA_IObject(CValue)
This class has no python functions
.. class:: SCA_ISensor(SCA_ILogicBrick)
Base class for all sensor logic bricks.
.. attribute:: usePosPulseMode
Flag to turn positive pulse mode on and off.
:type: boolean
.. attribute:: useNegPulseMode
Flag to turn negative pulse mode on and off.
:type: boolean
.. attribute:: frequency
The frequency for pulse mode sensors.
:type: integer
.. attribute:: level
level Option whether to detect level or edge transition when entering a state.
It makes a difference only in case of logic state transition (state actuator).
A level detector will immediately generate a pulse, negative or positive
depending on the sensor condition, as soon as the state is activated.
A edge detector will wait for a state change before generating a pulse.
note: mutually exclusive with :data:`tap`, enabling will disable :data:`tap`.
:type: boolean
.. attribute:: tap
When enabled only sensors that are just activated will send a positive event,
after this they will be detected as negative by the controllers.
This will make a key thats held act as if its only tapped for an instant.
note: mutually exclusive with :data:`level`, enabling will disable :data:`level`.
:type: boolean
.. attribute:: invert
Flag to set if this sensor activates on positive or negative events.
:type: boolean
.. attribute:: triggered
True if this sensor brick is in a positive state. (read-only).
:type: boolean
.. attribute:: positive
True if this sensor brick is in a positive state. (read-only).
:type: boolean
.. attribute:: status
The status of the sensor (read-only): can be one of :ref:`these constants<sensor-status>`.
:type: int
.. note::
This convenient attribute combines the values of triggered and positive attributes.
.. method:: reset()
Reset sensor internal state, effect depends on the type of sensor and settings.
The sensor is put in its initial state as if it was just activated.
.. class:: SCA_IController(SCA_ILogicBrick)
Base class for all controller logic bricks.
.. attribute:: state
The controllers state bitmask. This can be used with the GameObject's state to test if the controller is active.
:type: int bitmask
.. attribute:: sensors
A list of sensors linked to this controller.
:type: sequence supporting index/string lookups and iteration.
.. note::
The sensors are not necessarily owned by the same object.
.. note::
When objects are instanced in dupligroups links may be lost from objects outside the dupligroup.
.. attribute:: actuators
A list of actuators linked to this controller.
:type: sequence supporting index/string lookups and iteration.
.. note::
The sensors are not necessarily owned by the same object.
.. note::
When objects are instanced in dupligroups links may be lost from objects outside the dupligroup.
.. attribute:: useHighPriority
When set the controller executes always before all other controllers that dont have this set.
:type: boolen
.. note::
Order of execution between high priority controllers is not guaranteed.
.. class:: SCA_IActuator(SCA_ILogicBrick)
Base class for all actuator logic bricks.
.. class:: BL_ActionActuator(SCA_IActuator)
Action Actuators apply an action to an actor.
.. attribute:: action
The name of the action to set as the current action.
:type: string
.. attribute:: channelNames
A list of channel names that may be used with :data:`setChannel` and :data:`getChannel`.
:type: list of strings
.. attribute:: frameStart
Specifies the starting frame of the animation.
:type: float
.. attribute:: frameEnd
Specifies the ending frame of the animation.
:type: float
.. attribute:: blendIn
Specifies the number of frames of animation to generate when making transitions between actions.
:type: float
.. attribute:: priority
Sets the priority of this actuator. Actuators will lower priority numbers will override actuators with higher numbers.
:type: integer
.. attribute:: frame
Sets the current frame for the animation.
:type: float
.. attribute:: propName
Sets the property to be used in FromProp playback mode.
:type: string
.. attribute:: blendTime
Sets the internal frame timer. This property must be in the range from 0.0 to blendIn.
:type: float
.. attribute:: mode
The operation mode of the actuator. Can be one of :ref:`these constants<action-actuator>`.
:type: integer
.. attribute:: useContinue
The actions continue option, True or False. When True, the action will always play from where last left off, otherwise negative events to this actuator will reset it to its start frame.
:type: boolean
.. attribute:: framePropName
The name of the property that is set to the current frame number.
:type: string
.. method:: setChannel(channel, matrix)
Alternative to the 2 arguments, 4 arguments (channel, matrix, loc, size, quat) are also supported.
:arg channel: A string specifying the name of the bone channel, error raised if not in :data:`channelNames`.
:type channel: string
:arg matrix: A 4x4 matrix specifying the overriding transformation as an offset from the bone's rest position.
:arg matrix: list [[float]]
.. note::
These values are relative to the bones rest position, currently the api has no way to get this info (which is annoying), but can be worked around by using bones with a rest pose that has no translation.
.. method:: getChannel(channel)
:arg channel: A string specifying the name of the bone channel. error raised if not in :data:`channelNames`.
:type channel: string
:return: (loc, size, quat)
:rtype: tuple
.. class:: BL_Shader(PyObjectPlus)
BL_Shader GLSL shaders.
TODO - Description
.. method:: setUniformfv(name, fList)
Set a uniform with a list of float values
:arg name: the uniform name
:type name: string
:arg fList: a list (2, 3 or 4 elements) of float values
:type fList: list[float]
.. method:: delSource()
Clear the shader. Use this method before the source is changed with :data:`setSource`.
.. method:: getFragmentProg()
Returns the fragment program.
:return: The fragment program.
:rtype: string
.. method:: getVertexProg()
Get the vertex program.
:return: The vertex program.
:rtype: string
.. method:: isValid()
Check if the shader is valid.
:return: True if the shader is valid
:rtype: boolean
.. method:: setAttrib(enum)
Set attribute location. (The parameter is ignored a.t.m. and the value of "tangent" is always used.)
:arg enum: attribute location value
:type enum: integer
.. method:: setNumberOfPasses( max_pass )
Set the maximum number of passes. Not used a.t.m.
:arg max_pass: the maximum number of passes
:type max_pass: integer
.. method:: setSampler(name, index)
Set uniform texture sample index.
:arg name: Uniform name
:type name: string
:arg index: Texture sample index.
:type index: integer
.. method:: setSource(vertexProgram, fragmentProgram)
Set the vertex and fragment programs
:arg vertexProgram: Vertex program
:type vertexProgram: string
:arg fragmentProgram: Fragment program
:type fragmentProgram: string
.. method:: setUniform1f(name, fx)
Set a uniform with 1 float value.
:arg name: the uniform name
:type name: string
:arg fx: Uniform value
:type fx: float
.. method:: setUniform1i(name, ix)
Set a uniform with an integer value.
:arg name: the uniform name
:type name: string
:arg ix: the uniform value
:type ix: integer
.. method:: setUniform2f(name, fx, fy)
Set a uniform with 2 float values
:arg name: the uniform name
:type name: string
:arg fx: first float value
:type fx: float
:arg fy: second float value
:type fy: float
.. method:: setUniform2i(name, ix, iy)
Set a uniform with 2 integer values
:arg name: the uniform name
:type name: string
:arg ix: first integer value
:type ix: integer
:arg iy: second integer value
:type iy: integer
.. method:: setUniform3f(name, fx, fy, fz)
Set a uniform with 3 float values.
:arg name: the uniform name
:type name: string
:arg fx: first float value
:type fx: float
:arg fy: second float value
:type fy: float
:arg fz: third float value
:type fz: float
.. method:: setUniform3i(name, ix, iy, iz)
Set a uniform with 3 integer values
:arg name: the uniform name
:type name: string
:arg ix: first integer value
:type ix: integer
:arg iy: second integer value
:type iy: integer
:arg iz: third integer value
:type iz: integer
.. method:: setUniform4f(name, fx, fy, fz, fw)
Set a uniform with 4 float values.
:arg name: the uniform name
:type name: string
:arg fx: first float value
:type fx: float
:arg fy: second float value
:type fy: float
:arg fz: third float value
:type fz: float
:arg fw: fourth float value
:type fw: float
.. method:: setUniform4i(name, ix, iy, iz, iw)
Set a uniform with 4 integer values
:arg name: the uniform name
:type name: string
:arg ix: first integer value
:type ix: integer
:arg iy: second integer value
:type iy: integer
:arg iz: third integer value
:type iz: integer
:arg iw: fourth integer value
:type iw: integer
.. method:: setUniformDef(name, type)
Define a new uniform
:arg name: the uniform name
:type name: string
:arg type: uniform type
:type type: UNI_NONE, UNI_INT, UNI_FLOAT, UNI_INT2, UNI_FLOAT2, UNI_INT3, UNI_FLOAT3, UNI_INT4, UNI_FLOAT4, UNI_MAT3, UNI_MAT4, UNI_MAX
.. method:: setUniformMatrix3(name, mat, transpose)
Set a uniform with a 3x3 matrix value
:arg name: the uniform name
:type name: string
:arg mat: A 3x3 matrix [[f, f, f], [f, f, f], [f, f, f]]
:type mat: 3x3 matrix
:arg transpose: set to True to transpose the matrix
:type transpose: boolean
.. method:: setUniformMatrix4(name, mat, transpose)
Set a uniform with a 4x4 matrix value
:arg name: the uniform name
:type name: string
:arg mat: A 4x4 matrix [[f, f, f, f], [f, f, f, f], [f, f, f, f], [f, f, f, f]]
:type mat: 4x4 matrix
:arg transpose: set to True to transpose the matrix
:type transpose: boolean
.. method:: setUniformiv(name, iList)
Set a uniform with a list of integer values
:arg name: the uniform name
:type name: string
:arg iList: a list (2, 3 or 4 elements) of integer values
:type iList: list[integer]
.. method:: validate()
Validate the shader object.
.. class:: BL_ShapeActionActuator(SCA_IActuator)
ShapeAction Actuators apply an shape action to an mesh object.
.. attribute:: action
The name of the action to set as the current shape action.
:type: string
.. attribute:: frameStart
Specifies the starting frame of the shape animation.
:type: float
.. attribute:: frameEnd
Specifies the ending frame of the shape animation.
:type: float
.. attribute:: blendIn
Specifies the number of frames of animation to generate when making transitions between actions.
:type: float
.. attribute:: priority
Sets the priority of this actuator. Actuators will lower priority numbers will override actuators with higher numbers.
:type: integer
.. attribute:: frame
Sets the current frame for the animation.
:type: float
.. attribute:: propName
Sets the property to be used in FromProp playback mode.
:type: string
.. attribute:: blendTime
Sets the internal frame timer. This property must be in the range from 0.0 to blendin.
:type: float
.. attribute:: mode
The operation mode of the actuator. Can be one of :ref:`these constants<shape-action-actuator>`.
:type: integer
.. attribute:: framePropName
The name of the property that is set to the current frame number.
:type: string
.. class:: CListValue(CPropValue)
This is a list like object used in the game engine internally that behaves similar to a python list in most ways.
As well as the normal index lookup (``val= clist[i]``), CListValue supports string lookups (``val= scene.objects["Cube"]``)
Other operations such as ``len(clist)``, ``list(clist)``, ``clist[0:10]`` are also supported.
.. method:: append(val)
Add an item to the list (like pythons append)
.. warning::
Appending values to the list can cause crashes when the list is used internally by the game engine.
.. method:: count(val)
Count the number of instances of a value in the list.
:return: number of instances
:rtype: integer
.. method:: index(val)
Return the index of a value in the list.
:return: The index of the value in the list.
:rtype: integer
.. method:: reverse()
Reverse the order of the list.
.. method:: get(key, default=None)
Return the value matching key, or the default value if its not found.
:return: The key value or a default.
.. method:: from_id(id)
This is a funtion especially for the game engine to return a value with a spesific id.
Since object names are not always unique, the id of an object can be used to get an object from the CValueList.
Example:
.. code-block:: python
myObID=id(gameObject)
ob= scene.objects.from_id(myObID)
Where ``myObID`` is an int or long from the id function.
This has the advantage that you can store the id in places you could not store a gameObject.
.. warning::
The id is derived from a memory location and will be different each time the game engine starts.
.. class:: KX_BlenderMaterial(PyObjectPlus)
KX_BlenderMaterial
.. method:: getShader()
Returns the material's shader.
:return: the material's shader
:rtype: :class:`BL_Shader`
.. method:: setBlending(src, dest)
Set the pixel color arithmetic functions.
:arg src: Specifies how the red, green, blue, and alpha source blending factors are computed.
:type src: Value in...
* GL_ZERO,
* GL_ONE,
* GL_SRC_COLOR,
* GL_ONE_MINUS_SRC_COLOR,
* GL_DST_COLOR,
* GL_ONE_MINUS_DST_COLOR,
* GL_SRC_ALPHA,
* GL_ONE_MINUS_SRC_ALPHA,
* GL_DST_ALPHA,
* GL_ONE_MINUS_DST_ALPHA,
* GL_SRC_ALPHA_SATURATE
:arg dest: Specifies how the red, green, blue, and alpha destination blending factors are computed.
:type dest: Value in...
* GL_ZERO
* GL_ONE
* GL_SRC_COLOR
* GL_ONE_MINUS_SRC_COLOR
* GL_DST_COLOR
* GL_ONE_MINUS_DST_COLOR
* GL_SRC_ALPHA
* GL_ONE_MINUS_SRC_ALPHA
* GL_DST_ALPHA
* GL_ONE_MINUS_DST_ALPHA
* GL_SRC_ALPHA_SATURATE
.. method:: getMaterialIndex()
Returns the material's index.
:return: the material's index
:rtype: integer
.. class:: KX_CameraActuator(SCA_IActuator)
Applies changes to a camera.
.. attribute:: min
minimum distance to the target object maintained by the actuator.
:type: float
.. attribute:: max
maximum distance to stay from the target object.
:type: float
.. attribute:: height
height to stay above the target object.
:type: float
.. attribute:: useXY
axis this actuator is tracking, True=X, False=Y.
:type: boolean
.. attribute:: object
the object this actuator tracks.
:type: :class:`KX_GameObject` or None
.. class:: KX_ConstraintActuator(SCA_IActuator)
A constraint actuator limits the position, rotation, distance or orientation of an object.
.. attribute:: damp
Time constant of the constraint expressed in frame (not use by Force field constraint).
:type: integer
.. attribute:: rotDamp
Time constant for the rotation expressed in frame (only for the distance constraint), 0 = use damp for rotation as well.
:type: integer
.. attribute:: direction
The reference direction in world coordinate for the orientation constraint.
:type: 3-tuple of float: (x, y, z)
.. attribute:: option
Binary combination of :ref:`these constants <constraint-actuator-option>`
:type: integer
.. attribute:: time
activation time of the actuator. The actuator disables itself after this many frame. If set to 0, the actuator is not limited in time.
:type: integer
.. attribute:: propName
the name of the property or material for the ray detection of the distance constraint.
:type: string
.. attribute:: min
The lower bound of the constraint. For the rotation and orientation constraint, it represents radiant.
:type: float
.. attribute:: distance
the target distance of the distance constraint.
:type: float
.. attribute:: max
the upper bound of the constraint. For rotation and orientation constraints, it represents radiant.
:type: float
.. attribute:: rayLength
the length of the ray of the distance constraint.
:type: float
.. attribute:: limit
type of constraint. Use one of the :ref:`these constants <constraint-actuator-limit>`
:type: integer.
.. class:: KX_ConstraintWrapper(PyObjectPlus)
KX_ConstraintWrapper
.. method:: getConstraintId(val)
Returns the contraint's ID
:return: the constraint's ID
:rtype: integer
.. class:: KX_GameActuator(SCA_IActuator)
The game actuator loads a new .blend file, restarts the current .blend file or quits the game.
.. attribute:: fileName
the new .blend file to load.
:type: string
.. attribute:: mode
The mode of this actuator. Can be on of :ref:`these constants <game-actuator>`
:type: Int
.. class:: KX_GameObject(SCA_IObject)
All game objects are derived from this class.
Properties assigned to game objects are accessible as attributes of this class.
.. note::
Calling ANY method or attribute on an object that has been removed from a scene will raise a SystemError, if an object may have been removed since last accessing it use the :data:`invalid` attribute to check.
.. attribute:: name
The object's name. (read-only).
:type: string
.. attribute:: mass
The object's mass
:type: float
.. note::
The object must have a physics controller for the mass to be applied, otherwise the mass value will be returned as 0.0.
.. attribute:: linVelocityMin
Enforces the object keeps moving at a minimum velocity.
:type: float
.. note::
Applies to dynamic and rigid body objects only.
.. note::
A value of 0.0 disables this option.
.. note::
While objects are stationary the minimum velocity will not be applied.
.. attribute:: linVelocityMax
Clamp the maximum linear velocity to prevent objects moving beyond a set speed.
:type: float
.. note::
Applies to dynamic and rigid body objects only.
.. note::
A value of 0.0 disables this option (rather then setting it stationary).
.. attribute:: localInertia
the object's inertia vector in local coordinates. Read only.
:type: list [ix, iy, iz]
.. attribute:: parent
The object's parent object. (read-only).
:type: :class:`KX_GameObject` or None
.. attribute:: visible
visibility flag.
:type: boolean
.. note::
Game logic will still run for invisible objects.
.. attribute:: color
The object color of the object. [r, g, b, a]
:type: :class:`mathutils.Vector`
.. attribute:: occlusion
occlusion capability flag.
:type: boolean
.. attribute:: position
The object's position. [x, y, z] On write: local position, on read: world position
.. deprecated:: use :data:`localPosition` and :data:`worldPosition`.
:type: :class:`mathurils.Vector`
.. attribute:: orientation
The object's orientation. 3x3 Matrix. You can also write a Quaternion or Euler vector. On write: local orientation, on read: world orientation
.. deprecated:: use :data:`localOrientation` and :data:`worldOrientation`.
:type: :class:`mathutils.Matrix`
.. attribute:: scaling
The object's scaling factor. [sx, sy, sz] On write: local scaling, on read: world scaling
.. deprecated:: use :data:`localScale` and :data:`worldScale`.
:type: :class:`mathutils.Vector`
.. attribute:: localOrientation
The object's local orientation. 3x3 Matrix. You can also write a Quaternion or Euler vector.
:type: :class:`mathutils.Matrix`
.. attribute:: worldOrientation
The object's world orientation. 3x3 Matrix.
:type: :class:`mathutils.Matrix`
.. attribute:: localScale
The object's local scaling factor. [sx, sy, sz]
:type: :class:`mathutils.Vector`
.. attribute:: worldScale
The object's world scaling factor. Read-only. [sx, sy, sz]
:type: :class:`mathutils.Vector`
.. attribute:: localPosition
The object's local position. [x, y, z]
:type: :class:`mathutils.Vector`
.. attribute:: worldPosition
The object's world position. [x, y, z]
:type: :class:`mathutils.Vector`
.. attribute:: localLinearVelocity
The object's local linear velocity. [x, y, z]
:type: :class:`mathutils.Vector`
.. attribute:: worldLinearVelocity
The object's world linear velocity. [x, y, z]
:type: :class:`mathutils.Vector`
.. attribute:: localAngularVelocity
The object's local angular velocity. [x, y, z]
:type: :class:`mathutils.Vector`
.. attribute:: worldAngularVelocity
The object's world angular velocity. [x, y, z]
:type: :class:`mathutils.Vector`
.. attribute:: timeOffset
adjust the slowparent delay at runtime.
:type: float
.. attribute:: state
the game object's state bitmask, using the first 30 bits, one bit must always be set.
:type: int
.. attribute:: meshes
a list meshes for this object.
:type: list of :class:`KX_MeshProxy`
.. note::
Most objects use only 1 mesh.
.. note::
Changes to this list will not update the KX_GameObject.
.. attribute:: sensors
a sequence of :class:`SCA_ISensor` objects with string/index lookups and iterator support.
:type: list
.. note::
This attribute is experemental and may be removed (but probably wont be).
.. note::
Changes to this list will not update the KX_GameObject.
.. attribute:: controllers
a sequence of :class:`SCA_IController` objects with string/index lookups and iterator support.
:type: list of :class:`SCA_ISensor`
.. note::
This attribute is experemental and may be removed (but probably wont be).
.. note::
Changes to this list will not update the KX_GameObject.
.. attribute:: actuators
a list of :class:`SCA_IActuator` with string/index lookups and iterator support.
:type: list
.. note::
This attribute is experemental and may be removed (but probably wont be).
.. note::
Changes to this list will not update the KX_GameObject.
.. attribute:: attrDict
get the objects internal python attribute dictionary for direct (faster) access.
:type: dict
.. attribute:: children
direct children of this object, (read-only).
:type: :class:`CListValue` of :class:`KX_GameObject`'s
.. attribute:: childrenRecursive
all children of this object including childrens children, (read-only).
:type: :class:`CListValue` of :class:`KX_GameObject`'s
.. method:: endObject()
Delete this object, can be used in place of the EndObject Actuator.
The actual removal of the object from the scene is delayed.
.. method:: replaceMesh(mesh, useDisplayMesh=True, usePhysicsMesh=False)
Replace the mesh of this object with a new mesh. This works the same was as the actuator.
:arg mesh: mesh to replace or the meshes name.
:type mesh: :class:`MeshProxy` or string
:arg useDisplayMesh: when enabled the display mesh will be replaced (optional argument).
:type useDisplayMesh: boolean
:arg usePhysicsMesh: when enabled the physics mesh will be replaced (optional argument).
:type usePhysicsMesh: boolean
.. method:: setVisible(visible, recursive)
Sets the game object's visible flag.
:arg visible: the visible state to set.
:type visible: boolean
:arg recursive: optional argument to set all childrens visibility flag too.
:type recursive: boolean
.. method:: setOcclusion(occlusion, recursive)
Sets the game object's occlusion capability.
:arg occlusion: the state to set the occlusion to.
:type occlusion: boolean
:arg recursive: optional argument to set all childrens occlusion flag too.
:type recursive: boolean
.. method:: alignAxisToVect(vect, axis=2, factor=1.0)
Aligns any of the game object's axis along the given vector.
:arg vect: a vector to align the axis.
:type vect: 3D vector
:arg axis: The axis you want to align
* 0: X axis
* 1: Y axis
* 2: Z axis
:type axis: integer
:arg factor: Only rotate a feaction of the distance to the target vector (0.0 - 1.0)
:type factor: float
.. method:: getAxisVect(vect)
Returns the axis vector rotates by the objects worldspace orientation.
This is the equivalent of multiplying the vector by the orientation matrix.
:arg vect: a vector to align the axis.
:type vect: 3D Vector
:return: The vector in relation to the objects rotation.
:rtype: 3d vector.
.. method:: applyMovement(movement, local=False)
Sets the game object's movement.
:arg movement: movement vector.
:type movement: 3D Vector
:arg local:
* False: you get the "global" movement ie: relative to world orientation.
* True: you get the "local" movement ie: relative to object orientation.
:arg local: boolean
.. method:: applyRotation(rotation, local=False)
Sets the game object's rotation.
:arg rotation: rotation vector.
:type rotation: 3D Vector
:arg local:
* False: you get the "global" rotation ie: relative to world orientation.
* True: you get the "local" rotation ie: relative to object orientation.
:arg local: boolean
.. method:: applyForce(force, local=False)
Sets the game object's force.
This requires a dynamic object.
:arg force: force vector.
:type force: 3D Vector
:arg local:
* False: you get the "global" force ie: relative to world orientation.
* True: you get the "local" force ie: relative to object orientation.
:type local: boolean
.. method:: applyTorque(torque, local=False)
Sets the game object's torque.
This requires a dynamic object.
:arg torque: torque vector.
:type torque: 3D Vector
:arg local:
* False: you get the "global" torque ie: relative to world orientation.
* True: you get the "local" torque ie: relative to object orientation.
:type local: boolean
.. method:: getLinearVelocity(local=False)
Gets the game object's linear velocity.
This method returns the game object's velocity through it's centre of mass, ie no angular velocity component.
:arg local:
* False: you get the "global" velocity ie: relative to world orientation.
* True: you get the "local" velocity ie: relative to object orientation.
:type local: boolean
:return: the object's linear velocity.
:rtype: list [vx, vy, vz]
.. method:: setLinearVelocity(velocity, local=False)
Sets the game object's linear velocity.
This method sets game object's velocity through it's centre of mass,
ie no angular velocity component.
This requires a dynamic object.
:arg velocity: linear velocity vector.
:type velocity: 3D Vector
:arg local:
* False: you get the "global" velocity ie: relative to world orientation.
* True: you get the "local" velocity ie: relative to object orientation.
:type local: boolean
.. method:: getAngularVelocity(local=False)
Gets the game object's angular velocity.
:arg local:
* False: you get the "global" velocity ie: relative to world orientation.
* True: you get the "local" velocity ie: relative to object orientation.
:type local: boolean
:return: the object's angular velocity.
:rtype: list [vx, vy, vz]
.. method:: setAngularVelocity(velocity, local=False)
Sets the game object's angular velocity.
This requires a dynamic object.
:arg velocity: angular velocity vector.
:type velocity: boolean
:arg local:
* False: you get the "global" velocity ie: relative to world orientation.
* True: you get the "local" velocity ie: relative to object orientation.
.. method:: getVelocity(point=(0, 0, 0))
Gets the game object's velocity at the specified point.
Gets the game object's velocity at the specified point, including angular
components.
:arg point: optional point to return the velocity for, in local coordinates.
:type point: 3D Vector
:return: the velocity at the specified point.
:rtype: list [vx, vy, vz]
.. method:: getReactionForce()
Gets the game object's reaction force.
The reaction force is the force applied to this object over the last simulation timestep.
This also includes impulses, eg from collisions.
:return: the reaction force of this object.
:rtype: list [fx, fy, fz]
.. note::
This is not implimented at the moment.
.. method:: applyImpulse(point, impulse)
Applies an impulse to the game object.
This will apply the specified impulse to the game object at the specified point.
If point != position, applyImpulse will also change the object's angular momentum.
Otherwise, only linear momentum will change.
:arg point: the point to apply the impulse to (in world coordinates)
:type point: the point to apply the impulse to (in world coordinates)
.. method:: suspendDynamics()
Suspends physics for this object.
.. method:: restoreDynamics()
Resumes physics for this object.
.. note::
The objects linear velocity will be applied from when the dynamics were suspended.
.. method:: enableRigidBody()
Enables rigid body physics for this object.
Rigid body physics allows the object to roll on collisions.
.. note::
This is not working with bullet physics yet.
.. method:: disableRigidBody()
Disables rigid body physics for this object.
.. note::
This is not working with bullet physics yet. The angular is removed but rigid body physics can still rotate it later.
.. method:: setParent(parent, compound=True, ghost=True)
Sets this object's parent.
Control the shape status with the optional compound and ghost parameters:
In that case you can control if it should be ghost or not:
:arg parent: new parent object.
:type parent: :class:`KX_GameObject`
:arg compound: whether the shape should be added to the parent compound shape.
* True: the object shape should be added to the parent compound shape.
* False: the object should keep its individual shape.
:type compound: boolean
:arg ghost: whether the object should be ghost while parented.
* True: if the object should be made ghost while parented.
* False: if the object should be solid while parented.
:type ghost: boolean
.. note::
If the object type is sensor, it stays ghost regardless of ghost parameter
.. method:: removeParent()
Removes this objects parent.
.. method:: getPhysicsId()
Returns the user data object associated with this game object's physics controller.
.. method:: getPropertyNames()
Gets a list of all property names.
:return: All property names for this object.
:rtype: list
.. method:: getDistanceTo(other)
:arg other: a point or another :class:`KX_GameObject` to measure the distance to.
:type other: :class:`KX_GameObject` or list [x, y, z]
:return: distance to another object or point.
:rtype: float
.. method:: getVectTo(other)
Returns the vector and the distance to another object or point.
The vector is normalized unless the distance is 0, in which a zero length vector is returned.
:arg other: a point or another :class:`KX_GameObject` to get the vector and distance to.
:type other: :class:`KX_GameObject` or list [x, y, z]
:return: (distance, globalVector(3), localVector(3))
:rtype: 3-tuple (float, 3-tuple (x, y, z), 3-tuple (x, y, z))
.. method:: rayCastTo(other, dist, prop)
Look towards another point/object and find first object hit within dist that matches prop.
The ray is always casted from the center of the object, ignoring the object itself.
The ray is casted towards the center of another object or an explicit [x, y, z] point.
Use rayCast() if you need to retrieve the hit point
:arg other: [x, y, z] or object towards which the ray is casted
:type other: :class:`KX_GameObject` or 3-tuple
:arg dist: max distance to look (can be negative => look behind); 0 or omitted => detect up to other
:type dist: float
:arg prop: property name that object must have; can be omitted => detect any object
:type prop: string
:return: the first object hit or None if no object or object does not match prop
:rtype: :class:`KX_GameObject`
.. method:: rayCast(objto, objfrom, dist, prop, face, xray, poly)
Look from a point/object to another point/object and find first object hit within dist that matches prop.
if poly is 0, returns a 3-tuple with object reference, hit point and hit normal or (None, None, None) if no hit.
if poly is 1, returns a 4-tuple with in addition a :class:`KX_PolyProxy` as 4th element.
if poly is 2, returns a 5-tuple with in addition a 2D vector with the UV mapping of the hit point as 5th element.
.. code-block:: python
# shoot along the axis gun-gunAim (gunAim should be collision-free)
obj, point, normal = gun.rayCast(gunAim, None, 50)
if obj:
# do something
pass
The face paremeter determines the orientation of the normal.
* 0 => hit normal is always oriented towards the ray origin (as if you casted the ray from outside)
* 1 => hit normal is the real face normal (only for mesh object, otherwise face has no effect)
The ray has X-Ray capability if xray parameter is 1, otherwise the first object hit (other than self object) stops the ray.
The prop and xray parameters interact as follow.
* prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray.
* prop off, xray on : idem.
* prop on, xray off: return closest hit if it matches prop, no hit otherwise.
* prop on, xray on : return closest hit matching prop or no hit if there is no object matching prop on the full extend of the ray.
The :class:`KX_PolyProxy` 4th element of the return tuple when poly=1 allows to retrieve information on the polygon hit by the ray.
If there is no hit or the hit object is not a static mesh, None is returned as 4th element.
The ray ignores collision-free objects and faces that dont have the collision flag enabled, you can however use ghost objects.
:arg objto: [x, y, z] or object to which the ray is casted
:type objto: :class:`KX_GameObject` or 3-tuple
:arg objfrom: [x, y, z] or object from which the ray is casted; None or omitted => use self object center
:type objfrom: :class:`KX_GameObject` or 3-tuple or None
:arg dist: max distance to look (can be negative => look behind); 0 or omitted => detect up to to
:type dist: float
:arg prop: property name that object must have; can be omitted or "" => detect any object
:type prop: string
:arg face: normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin
:type face: integer
:arg xray: X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object
:type xray: integer
:arg poly: polygon option: 0, 1 or 2 to return a 3-, 4- or 5-tuple with information on the face hit.
* 0 or omitted: return value is a 3-tuple (object, hitpoint, hitnormal) or (None, None, None) if no hit
* 1: return value is a 4-tuple and the 4th element is a :class:`KX_PolyProxy` or None if no hit or the object doesn't use a mesh collision shape.
* 2: return value is a 5-tuple and the 5th element is a 2-tuple (u, v) with the UV mapping of the hit point or None if no hit, or the object doesn't use a mesh collision shape, or doesn't have a UV mapping.
:type poly: integer
:return: (object, hitpoint, hitnormal) or (object, hitpoint, hitnormal, polygon) or (object, hitpoint, hitnormal, polygon, hituv).
* object, hitpoint and hitnormal are None if no hit.
* polygon is valid only if the object is valid and is a static object, a dynamic object using mesh collision shape or a soft body object, otherwise it is None
* hituv is valid only if polygon is valid and the object has a UV mapping, otherwise it is None
:rtype:
* 3-tuple (:class:`KX_GameObject`, 3-tuple (x, y, z), 3-tuple (nx, ny, nz))
* or 4-tuple (:class:`KX_GameObject`, 3-tuple (x, y, z), 3-tuple (nx, ny, nz), :class:`PolyProxy`)
* or 5-tuple (:class:`KX_GameObject`, 3-tuple (x, y, z), 3-tuple (nx, ny, nz), :class:`PolyProxy`, 2-tuple (u, v))
.. note::
The ray ignores the object on which the method is called. It is casted from/to object center or explicit [x, y, z] points.
.. method:: setCollisionMargin(margin)
Set the objects collision margin.
:arg margin: the collision margin distance in blender units.
:type margin: float
.. note::
If this object has no physics controller (a physics ID of zero), this function will raise RuntimeError.
.. method:: sendMessage(subject, body="", to="")
Sends a message.
:arg subject: The subject of the message
:type subject: string
:arg body: The body of the message (optional)
:type body: string
:arg to: The name of the object to send the message to (optional)
:type to: string
.. method:: reinstancePhysicsMesh(gameObject, meshObject)
Updates the physics system with the changed mesh.
If no arguments are given the physics mesh will be re-created from the first mesh assigned to the game object.
:arg gameObject: optional argument, set the physics shape from this gameObjets mesh.
:type gameObject: string, :class:`KX_GameObject` or None
:arg meshObject: optional argument, set the physics shape from this mesh.
:type meshObject: string, :class:`MeshProxy` or None
:return: True if reinstance succeeded, False if it failed.
:rtype: boolean
.. note::
If this object has instances the other instances will be updated too.
.. note::
The gameObject argument has an advantage that it can convert from a mesh with modifiers applied (such as subsurf).
.. warning::
Only triangle mesh type objects are supported currently (not convex hull)
.. warning::
If the object is a part of a combound object it will fail (parent or child)
.. warning::
Rebuilding the physics mesh can be slow, running many times per second will give a performance hit.
.. method:: get(key, default=None)
Return the value matching key, or the default value if its not found.
:return: The key value or a default.
.. class:: KX_IpoActuator(SCA_IActuator)
IPO actuator activates an animation.
.. attribute:: frameStart
Start frame.
:type: float
.. attribute:: frameEnd
End frame.
:type: float
.. attribute:: propName
Use this property to define the Ipo position.
:type: string
.. attribute:: framePropName
Assign this property this action current frame number.
:type: string
.. attribute:: mode
Play mode for the ipo. Can be on of :ref:`these constants <ipo-actuator>`
:type: integer
.. attribute:: useIpoAsForce
Apply Ipo as a global or local force depending on the local option (dynamic objects only).
:type: boolean
.. attribute:: useIpoAdd
Ipo is added to the current loc/rot/scale in global or local coordinate according to Local flag.
:type: boolean
.. attribute:: useIpoLocal
Let the ipo acts in local coordinates, used in Force and Add mode.
:type: boolean
.. attribute:: useChildren
Update IPO on all children Objects as well.
:type: boolean
.. class:: KX_LightObject(KX_GameObject)
A Light object.
.. code-block:: python
# Turn on a red alert light.
import bge
co = bge.logic.getCurrentController()
light = co.owner
light.energy = 1.0
light.colour = [1.0, 0.0, 0.0]
.. data:: SPOT
A spot light source. See attribute :data:`type`
.. data:: SUN
A point light source with no attenuation. See attribute :data:`type`
.. data:: NORMAL
A point light source. See attribute :data:`type`
.. attribute:: type
The type of light - must be SPOT, SUN or NORMAL
.. attribute:: layer
The layer mask that this light affects object on.
:type: bitfield
.. attribute:: energy
The brightness of this light.
:type: float
.. attribute:: distance
The maximum distance this light can illuminate. (SPOT and NORMAL lights only).
:type: float
.. attribute:: colour
The colour of this light. Black = [0.0, 0.0, 0.0], White = [1.0, 1.0, 1.0].
:type: list [r, g, b]
.. attribute:: color
Synonym for colour.
.. attribute:: lin_attenuation
The linear component of this light's attenuation. (SPOT and NORMAL lights only).
:type: float
.. attribute:: quad_attenuation
The quadratic component of this light's attenuation (SPOT and NORMAL lights only).
:type: float
.. attribute:: spotsize
The cone angle of the spot light, in degrees (SPOT lights only).
:type: float in [0 - 180].
.. attribute:: spotblend
Specifies the intensity distribution of the spot light (SPOT lights only).
:type: float in [0 - 1]
.. note::
Higher values result in a more focused light source.
.. class:: KX_MeshProxy(SCA_IObject)
A mesh object.
You can only change the vertex properties of a mesh object, not the mesh topology.
To use mesh objects effectively, you should know a bit about how the game engine handles them.
#. Mesh Objects are converted from Blender at scene load.
#. The Converter groups polygons by Material. This means they can be sent to the renderer efficiently. A material holds:
#. The texture.
#. The Blender material.
#. The Tile properties
#. The face properties - (From the "Texture Face" panel)
#. Transparency & z sorting
#. Light layer
#. Polygon shape (triangle/quad)
#. Game Object
#. Verticies will be split by face if necessary. Verticies can only be shared between faces if:
#. They are at the same position
#. UV coordinates are the same
#. Their normals are the same (both polygons are "Set Smooth")
#. They are the same colour, for example: a cube has 24 verticies: 6 faces with 4 verticies per face.
The correct method of iterating over every :class:`KX_VertexProxy` in a game object
.. code-block:: python
import GameLogic
co = GameLogic.getCurrentController()
obj = co.owner
m_i = 0
mesh = obj.getMesh(m_i) # There can be more than one mesh...
while mesh != None:
for mat in range(mesh.getNumMaterials()):
for v_index in range(mesh.getVertexArrayLength(mat)):
vertex = mesh.getVertex(mat, v_index)
# Do something with vertex here...
# ... eg: colour the vertex red.
vertex.colour = [1.0, 0.0, 0.0, 1.0]
m_i += 1
mesh = obj.getMesh(m_i)
.. attribute:: materials
:type: list of :class:`KX_BlenderMaterial` or :class:`KX_PolygonMaterial` types
.. attribute:: numPolygons
:type: integer
.. attribute:: numMaterials
:type: integer
.. method:: getNumMaterials()
:return: number of materials associated with this object
:rtype: integer
.. method:: getMaterialName(matid)
Gets the name of the specified material.
:arg matid: the specified material.
:type matid: integer
:return: the attached material name.
:rtype: string
.. method:: getTextureName(matid)
Gets the name of the specified material's texture.
:arg matid: the specified material
:type matid: integer
:return: the attached material's texture name.
:rtype: string
.. method:: getVertexArrayLength(matid)
Gets the length of the vertex array associated with the specified material.
There is one vertex array for each material.
:arg matid: the specified material
:type matid: integer
:return: the number of verticies in the vertex array.
:rtype: integer
.. method:: getVertex(matid, index)
Gets the specified vertex from the mesh object.
:arg matid: the specified material
:type matid: integer
:arg index: the index into the vertex array.
:type index: integer
:return: a vertex object.
:rtype: :class:`KX_VertexProxy`
.. method:: getNumPolygons()
:return: The number of polygon in the mesh.
:rtype: integer
.. method:: getPolygon(index)
Gets the specified polygon from the mesh.
:arg index: polygon number
:type index: integer
:return: a polygon object.
:rtype: :class:`PolyProxy`
.. class:: SCA_MouseSensor(SCA_ISensor)
Mouse Sensor logic brick.
.. attribute:: position
current [x, y] coordinates of the mouse, in frame coordinates (pixels).
:type: [integer, interger]
.. attribute:: mode
sensor mode.
:type: integer
* KX_MOUSESENSORMODE_LEFTBUTTON(1)
* KX_MOUSESENSORMODE_MIDDLEBUTTON(2)
* KX_MOUSESENSORMODE_RIGHTBUTTON(3)
* KX_MOUSESENSORMODE_WHEELUP(4)
* KX_MOUSESENSORMODE_WHEELDOWN(5)
* KX_MOUSESENSORMODE_MOVEMENT(6)
.. method:: getButtonStatus(button)
Get the mouse button status.
:arg button: The code that represents the key you want to get the state of, use one of :ref:`these constants<mouse-keys>`
:type button: int
:return: The state of the given key, can be one of :ref:`these constants<input-status>`
:rtype: int
.. class:: KX_MouseFocusSensor(SCA_MouseSensor)
The mouse focus sensor detects when the mouse is over the current game object.
The mouse focus sensor works by transforming the mouse coordinates from 2d device
space to 3d space then raycasting away from the camera.
.. attribute:: raySource
The worldspace source of the ray (the view position).
:type: list (vector of 3 floats)
.. attribute:: rayTarget
The worldspace target of the ray.
:type: list (vector of 3 floats)
.. attribute:: rayDirection
The :data:`rayTarget` - :class:`raySource` normalized.
:type: list (normalized vector of 3 floats)
.. attribute:: hitObject
the last object the mouse was over.
:type: :class:`KX_GameObject` or None
.. attribute:: hitPosition
The worldspace position of the ray intersecton.
:type: list (vector of 3 floats)
.. attribute:: hitNormal
the worldspace normal from the face at point of intersection.
:type: list (normalized vector of 3 floats)
.. attribute:: hitUV
the UV coordinates at the point of intersection.
:type: list (vector of 2 floats)
If the object has no UV mapping, it returns [0, 0].
The UV coordinates are not normalized, they can be < 0 or > 1 depending on the UV mapping.
.. attribute:: usePulseFocus
When enabled, moving the mouse over a different object generates a pulse. (only used when the 'Mouse Over Any' sensor option is set).
:type: boolean
.. class:: KX_TouchSensor(SCA_ISensor)
Touch sensor detects collisions between objects.
.. attribute:: propName
The property or material to collide with.
:type: string
.. attribute:: useMaterial
Determines if the sensor is looking for a property or material. KX_True = Find material; KX_False = Find property.
:type: boolean
.. attribute:: usePulseCollision
When enabled, changes to the set of colliding objects generate a pulse.
:type: boolean
.. attribute:: hitObject
The last collided object. (read-only).
:type: :class:`KX_GameObject` or None
.. attribute:: hitObjectList
A list of colliding objects. (read-only).
:type: :class:`CListValue` of :class:`KX_GameObject`
.. class:: KX_NearSensor(KX_TouchSensor)
A near sensor is a specialised form of touch sensor.
.. attribute:: distance
The near sensor activates when an object is within this distance.
:type: float
.. attribute:: resetDistance
The near sensor deactivates when the object exceeds this distance.
:type: float
.. class:: KX_NetworkMessageActuator(SCA_IActuator)
Message Actuator
.. attribute:: propName
Messages will only be sent to objects with the given property name.
:type: string
.. attribute:: subject
The subject field of the message.
:type: string
.. attribute:: body
The body of the message.
:type: string
.. attribute:: usePropBody
Send a property instead of a regular body message.
:type: boolean
.. class:: KX_NetworkMessageSensor(SCA_ISensor)
The Message Sensor logic brick.
Currently only loopback (local) networks are supported.
.. attribute:: subject
The subject the sensor is looking for.
:type: string
.. attribute:: frameMessageCount
The number of messages received since the last frame. (read-only).
:type: integer
.. attribute:: subjects
The list of message subjects received. (read-only).
:type: list of strings
.. attribute:: bodies
The list of message bodies received. (read-only).
:type: list of strings
.. class:: KX_ObjectActuator(SCA_IActuator)
The object actuator ("Motion Actuator") applies force, torque, displacement, angular displacement,
velocity, or angular velocity to an object.
Servo control allows to regulate force to achieve a certain speed target.
.. attribute:: force
The force applied by the actuator.
:type: list [x, y, z]
.. attribute:: useLocalForce
A flag specifying if the force is local.
:type: boolean
.. attribute:: torque
The torque applied by the actuator.
:type: list [x, y, z]
.. attribute:: useLocalTorque
A flag specifying if the torque is local.
:type: boolean
.. attribute:: dLoc
The displacement vector applied by the actuator.
:type: list [x, y, z]
.. attribute:: useLocalDLoc
A flag specifying if the dLoc is local.
:type: boolean
.. attribute:: dRot
The angular displacement vector applied by the actuator
:type: list [x, y, z]
.. note::
Since the displacement is applied every frame, you must adjust the displacement based on the frame rate, or you game experience will depend on the player's computer speed.
.. attribute:: useLocalDRot
A flag specifying if the dRot is local.
:type: boolean
.. attribute:: linV
The linear velocity applied by the actuator.
:type: list [x, y, z]
.. attribute:: useLocalLinV
A flag specifying if the linear velocity is local.
:type: boolean
.. note::
This is the target speed for servo controllers.
.. attribute:: angV
The angular velocity applied by the actuator.
:type: list [x, y, z]
.. attribute:: useLocalAngV
A flag specifying if the angular velocity is local.
:type: boolean
.. attribute:: damping
The damping parameter of the servo controller.
:type: short
.. attribute:: forceLimitX
The min/max force limit along the X axis and activates or deactivates the limits in the servo controller.
:type: list [min(float), max(float), bool]
.. attribute:: forceLimitY
The min/max force limit along the Y axis and activates or deactivates the limits in the servo controller.
:type: list [min(float), max(float), bool]
.. attribute:: forceLimitZ
The min/max force limit along the Z axis and activates or deactivates the limits in the servo controller.
:type: list [min(float), max(float), bool]
.. attribute:: pid
The PID coefficients of the servo controller.
:type: list of floats [proportional, integral, derivate]
.. attribute:: reference
The object that is used as reference to compute the velocity for the servo controller.
:type: :class:`KX_GameObject` or None
.. class:: KX_ParentActuator(SCA_IActuator)
The parent actuator can set or remove an objects parent object.
.. attribute:: object
the object this actuator sets the parent too.
:type: :class:`KX_GameObject` or None
.. attribute:: mode
The mode of this actuator.
:type: integer from 0 to 1.
.. attribute:: compound
Whether the object shape should be added to the parent compound shape when parenting.
Effective only if the parent is already a compound shape.
:type: boolean
.. attribute:: ghost
Whether the object should be made ghost when parenting
Effective only if the shape is not added to the parent compound shape.
:type: boolean
.. class:: KX_PhysicsObjectWrapper(PyObjectPlus)
KX_PhysicsObjectWrapper
.. method:: setActive(active)
Set the object to be active.
:arg active: set to True to be active
:type active: boolean
.. method:: setAngularVelocity(x, y, z, local)
Set the angular velocity of the object.
:arg x: angular velocity for the x-axis
:type x: float
:arg y: angular velocity for the y-axis
:type y: float
:arg z: angular velocity for the z-axis
:type z: float
:arg local: set to True for local axis
:type local: boolean
.. method:: setLinearVelocity(x, y, z, local)
Set the linear velocity of the object.
:arg x: linear velocity for the x-axis
:type x: float
:arg y: linear velocity for the y-axis
:type y: float
:arg z: linear velocity for the z-axis
:type z: float
:arg local: set to True for local axis
:type local: boolean
.. class:: KX_PolyProxy(SCA_IObject)
A polygon holds the index of the vertex forming the poylgon.
Note:
The polygon attributes are read-only, you need to retrieve the vertex proxy if you want
to change the vertex settings.
.. attribute:: matname
The name of polygon material, empty if no material.
:type: string
.. attribute:: material
The material of the polygon.
:type: :class:`KX_PolygonMaterial` or :class:`KX_BlenderMaterial`
.. attribute:: texture
The texture name of the polygon.
:type: string
.. attribute:: matid
The material index of the polygon, use this to retrieve vertex proxy from mesh proxy.
:type: integer
.. attribute:: v1
vertex index of the first vertex of the polygon, use this to retrieve vertex proxy from mesh proxy.
:type: integer
.. attribute:: v2
vertex index of the second vertex of the polygon, use this to retrieve vertex proxy from mesh proxy.
:type: integer
.. attribute:: v3
vertex index of the third vertex of the polygon, use this to retrieve vertex proxy from mesh proxy.
:type: integer
.. attribute:: v4
Vertex index of the fourth vertex of the polygon, 0 if polygon has only 3 vertex
Use this to retrieve vertex proxy from mesh proxy.
:type: integer
.. attribute:: visible
visible state of the polygon: 1=visible, 0=invisible.
:type: integer
.. attribute:: collide
collide state of the polygon: 1=receives collision, 0=collision free.
:type: integer
.. method:: getMaterialName()
Returns the polygon material name with MA prefix
:return: material name
:rtype: string
.. method:: getMaterial()
:return: The polygon material
:rtype: :class:`KX_PolygonMaterial` or :class:`KX_BlenderMaterial`
.. method:: getTextureName()
:return: The texture name
:rtype: string
.. method:: getMaterialIndex()
Returns the material bucket index of the polygon.
This index and the ones returned by getVertexIndex() are needed to retrieve the vertex proxy from :class:`MeshProxy`.
:return: the material index in the mesh
:rtype: integer
.. method:: getNumVertex()
Returns the number of vertex of the polygon.
:return: number of vertex, 3 or 4.
:rtype: integer
.. method:: isVisible()
Returns whether the polygon is visible or not
:return: 0=invisible, 1=visible
:rtype: boolean
.. method:: isCollider()
Returns whether the polygon is receives collision or not
:return: 0=collision free, 1=receives collision
:rtype: integer
.. method:: getVertexIndex(vertex)
Returns the mesh vertex index of a polygon vertex
This index and the one returned by getMaterialIndex() are needed to retrieve the vertex proxy from :class:`MeshProxy`.
:arg vertex: index of the vertex in the polygon: 0->3
:arg vertex: integer
:return: mesh vertex index
:rtype: integer
.. method:: getMesh()
Returns a mesh proxy
:return: mesh proxy
:rtype: :class:`MeshProxy`
.. class:: KX_PolygonMaterial(PyObjectPlus)
This is the interface to materials in the game engine.
Materials define the render state to be applied to mesh objects.
.. warning::
Some of the methods/variables are CObjects. If you mix these up, you will crash blender.
This example requires `PyOpenGL <http://pyopengl.sourceforge.net>`_ and `GLEWPy <http://glewpy.sourceforge.net>`_
.. code-block:: python
import GameLogic
import OpenGL
from OpenGL.GL import *
from OpenGL.GLU import *
import glew
from glew import *
glewInit()
vertex_shader = """
void main(void)
{
gl_Position = ftransform();
}
"""
fragment_shader ="""
void main(void)
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
"""
class MyMaterial:
def __init__(self):
self.pass_no = 0
# Create a shader
self.m_program = glCreateProgramObjectARB()
# Compile the vertex shader
self.shader(GL_VERTEX_SHADER_ARB, (vertex_shader))
# Compile the fragment shader
self.shader(GL_FRAGMENT_SHADER_ARB, (fragment_shader))
# Link the shaders together
self.link()
def PrintInfoLog(self, tag, object):
"""
PrintInfoLog prints the GLSL compiler log
"""
print "Tag: def PrintGLError(self, tag = ""):
def PrintGLError(self, tag = ""):
"""
Prints the current GL error status
"""
if len(tag):
print tag
err = glGetError()
if err != GL_NO_ERROR:
print "GL Error: %s\\n"%(gluErrorString(err))
def shader(self, type, shaders):
"""
shader compiles a GLSL shader and attaches it to the current
program.
type should be either GL_VERTEX_SHADER_ARB or GL_FRAGMENT_SHADER_ARB
shaders should be a sequence of shader source to compile.
"""
# Create a shader object
shader_object = glCreateShaderObjectARB(type)
# Add the source code
glShaderSourceARB(shader_object, len(shaders), shaders)
# Compile the shader
glCompileShaderARB(shader_object)
# Print the compiler log
self.PrintInfoLog("vertex shader", shader_object)
# Check if compiled, and attach if it did
compiled = glGetObjectParameterivARB(shader_object, GL_OBJECT_COMPILE_STATUS_ARB)
if compiled:
glAttachObjectARB(self.m_program, shader_object)
# Delete the object (glAttachObjectARB makes a copy)
glDeleteObjectARB(shader_object)
# print the gl error log
self.PrintGLError()
def link(self):
"""
Links the shaders together.
"""
# clear error indicator
glGetError()
glLinkProgramARB(self.m_program)
self.PrintInfoLog("link", self.m_program)
linked = glGetObjectParameterivARB(self.m_program, GL_OBJECT_LINK_STATUS_ARB)
if not linked:
print "Shader failed to link"
return
glValidateProgramARB(self.m_program)
valid = glGetObjectParameterivARB(self.m_program, GL_OBJECT_VALIDATE_STATUS_ARB)
if not valid:
print "Shader failed to validate"
return
def activate(self, rasty, cachingInfo, mat):
self.pass_no+=1
if (self.pass_no == 1):
glDisable(GL_COLOR_MATERIAL)
glUseProgramObjectARB(self.m_program)
return True
glEnable(GL_COLOR_MATERIAL)
glUseProgramObjectARB(0)
self.pass_no = 0
return False
obj = GameLogic.getCurrentController().owner
mesh = obj.meshes[0]
for mat in mesh.materials:
mat.setCustomMaterial(MyMaterial())
print mat.texture
.. attribute:: texture
Texture name.
:type: string (read-only)
.. attribute:: gl_texture
OpenGL texture handle (eg for glBindTexture(GL_TEXTURE_2D, gl_texture).
:type: integer (read-only)
.. attribute:: material
Material name.
:type: string (read-only)
.. attribute:: tface
Texture face properties.
:type: CObject (read-only)
.. attribute:: tile
Texture is tiling.
:type: boolean
.. attribute:: tilexrep
Number of tile repetitions in x direction.
:type: integer
.. attribute:: tileyrep
Number of tile repetitions in y direction.
:type: integer
.. attribute:: drawingmode
Drawing mode for the material.
- 2 (drawingmode & 4) Textured
- 4 (drawingmode & 16) Light
- 14 (drawingmode & 16384) 3d Polygon Text.
:type: bitfield
.. attribute:: transparent
This material is transparent. All meshes with this
material will be rendered after non transparent meshes from back
to front.
:type: boolean
.. attribute:: zsort
Transparent polygons in meshes with this material will be sorted back to
front before rendering.
Non-Transparent polygons will be sorted front to back before rendering.
:type: boolean
.. attribute:: lightlayer
Light layers this material affects.
:type: bitfield.
.. attribute:: triangle
Mesh data with this material is triangles. It's probably not safe to change this.
:type: boolean
.. attribute:: diffuse
The diffuse colour of the material. black = [0.0, 0.0, 0.0] white = [1.0, 1.0, 1.0].
:type: list [r, g, b]
.. attribute:: specular
The specular colour of the material. black = [0.0, 0.0, 0.0] white = [1.0, 1.0, 1.0].
:type: list [r, g, b]
.. attribute:: shininess
The shininess (specular exponent) of the material. 0.0 <= shininess <= 128.0.
:type: float
.. attribute:: specularity
The amount of specular of the material. 0.0 <= specularity <= 1.0.
:type: float
.. method:: updateTexture(tface, rasty)
Updates a realtime animation.
:arg tface: Texture face (eg mat.tface)
:type tface: CObject
:arg rasty: Rasterizer
:type rasty: CObject
.. method:: setTexture(tface)
Sets texture render state.
:arg tface: Texture face
:type tface: CObject
.. code-block:: python
mat.setTexture(mat.tface)
.. method:: activate(rasty, cachingInfo)
Sets material parameters for this object for rendering.
Material Parameters set:
#. Texture
#. Backface culling
#. Line drawing
#. Specular Colour
#. Shininess
#. Diffuse Colour
#. Polygon Offset.
:arg rasty: Rasterizer instance.
:type rasty: CObject
:arg cachingInfo: Material cache instance.
:type cachingInfo: CObject
.. method:: setCustomMaterial(material)
Sets the material state setup object.
Using this method, you can extend or completely replace the gameengine material
to do your own advanced multipass effects.
Use this method to register your material class. Instead of the normal material,
your class's activate method will be called just before rendering the mesh.
This should setup the texture, material, and any other state you would like.
It should return True to render the mesh, or False if you are finished. You should
clean up any state Blender does not set before returning False.
Activate Method Definition:
.. code-block:: python
def activate(self, rasty, cachingInfo, material):
:arg material: The material object.
:type material: instance
.. code-block:: python
class PyMaterial:
def __init__(self):
self.pass_no = -1
def activate(self, rasty, cachingInfo, material):
# Activate the material here.
#
# The activate method will be called until it returns False.
# Every time the activate method returns True the mesh will
# be rendered.
#
# rasty is a CObject for passing to material.updateTexture()
# and material.activate()
# cachingInfo is a CObject for passing to material.activate()
# material is the KX_PolygonMaterial instance this material
# was added to
# default material properties:
self.pass_no += 1
if self.pass_no == 0:
material.activate(rasty, cachingInfo)
# Return True to do this pass
return True
# clean up and return False to finish.
self.pass_no = -1
return False
# Create a new Python Material and pass it to the renderer.
mat.setCustomMaterial(PyMaterial())
.. class:: KX_RadarSensor(KX_NearSensor)
Radar sensor is a near sensor with a conical sensor object.
.. attribute:: coneOrigin
The origin of the cone with which to test. The origin is in the middle of the cone. (read-only).
:type: list of floats [x, y, z]
.. attribute:: coneTarget
The center of the bottom face of the cone with which to test. (read-only).
:type: list of floats [x, y, z]
.. attribute:: distance
The height of the cone with which to test.
:type: float
.. attribute:: angle
The angle of the cone (in degrees) with which to test.
:type: float from 0 to 360
.. attribute:: axis
The axis on which the radar cone is cast.
:type: integer from 0 to 5
KX_RADAR_AXIS_POS_X, KX_RADAR_AXIS_POS_Y, KX_RADAR_AXIS_POS_Z,
KX_RADAR_AXIS_NEG_X, KX_RADAR_AXIS_NEG_Y, KX_RADAR_AXIS_NEG_Z
.. method:: getConeHeight()
:return: The height of the cone with which to test.
:rtype: float
.. class:: KX_RaySensor(SCA_ISensor)
A ray sensor detects the first object in a given direction.
.. attribute:: propName
The property the ray is looking for.
:type: string
.. attribute:: range
The distance of the ray.
:type: float
.. attribute:: useMaterial
Whether or not to look for a material (false = property).
:type: boolean
.. attribute:: useXRay
Whether or not to use XRay.
:type: boolean
.. attribute:: hitObject
The game object that was hit by the ray. (read-only).
:type: :class:`KX_GameObject`
.. attribute:: hitPosition
The position (in worldcoordinates) where the object was hit by the ray. (read-only).
:type: list [x, y, z]
.. attribute:: hitNormal
The normal (in worldcoordinates) of the object at the location where the object was hit by the ray. (read-only).
:type: list [x, y, z]
.. attribute:: rayDirection
The direction from the ray (in worldcoordinates). (read-only).
:type: list [x, y, z]
.. attribute:: axis
The axis the ray is pointing on.
:type: integer from 0 to 5
* KX_RAY_AXIS_POS_X
* KX_RAY_AXIS_POS_Y
* KX_RAY_AXIS_POS_Z
* KX_RAY_AXIS_NEG_X
* KX_RAY_AXIS_NEG_Y
* KX_RAY_AXIS_NEG_Z
.. class:: KX_SCA_AddObjectActuator(SCA_IActuator)
Edit Object Actuator (in Add Object Mode)
.. warning::
An Add Object actuator will be ignored if at game start, the linked object doesn't exist (or is empty) or the linked object is in an active layer.
.. code-block:: none
Error: GameObject 'Name' has a AddObjectActuator 'ActuatorName' without object (in 'nonactive' layer)
.. attribute:: object
the object this actuator adds.
:type: :class:`KX_GameObject` or None
.. attribute:: objectLastCreated
the last added object from this actuator (read-only).
:type: :class:`KX_GameObject` or None
.. attribute:: time
the lifetime of added objects, in frames. Set to 0 to disable automatic deletion.
:type: integer
.. attribute:: linearVelocity
the initial linear velocity of added objects.
:type: list [vx, vy, vz]
.. attribute:: angularVelocity
the initial angular velocity of added objects.
:type: list [vx, vy, vz]
.. method:: instantAddObject()
adds the object without needing to calling SCA_PythonController.activate()
.. note:: Use objectLastCreated to get the newly created object.
.. class:: KX_SCA_DynamicActuator(SCA_IActuator)
Dynamic Actuator.
.. attribute:: mode
:type: integer
the type of operation of the actuator, 0-4
* KX_DYN_RESTORE_DYNAMICS(0)
* KX_DYN_DISABLE_DYNAMICS(1)
* KX_DYN_ENABLE_RIGID_BODY(2)
* KX_DYN_DISABLE_RIGID_BODY(3)
* KX_DYN_SET_MASS(4)
.. attribute:: mass
the mass value for the KX_DYN_SET_MASS operation.
:type: float
.. class:: KX_SCA_EndObjectActuator(SCA_IActuator)
Edit Object Actuator (in End Object mode)
This actuator has no python methods.
.. class:: KX_SCA_ReplaceMeshActuator(SCA_IActuator)
Edit Object actuator, in Replace Mesh mode.
.. warning::
Replace mesh actuators will be ignored if at game start, the named mesh doesn't exist.
This will generate a warning in the console
.. code-block:: none
Error: GameObject 'Name' ReplaceMeshActuator 'ActuatorName' without object
.. code-block:: python
# Level-of-detail
# Switch a game object's mesh based on its depth in the camera view.
# +----------+ +-----------+ +-------------------------------------+
# | Always +-----+ Python +-----+ Edit Object (Replace Mesh) LOD.Mesh |
# +----------+ +-----------+ +-------------------------------------+
import GameLogic
# List detail meshes here
# Mesh (name, near, far)
# Meshes overlap so that they don't 'pop' when on the edge of the distance.
meshes = ((".Hi", 0.0, -20.0),
(".Med", -15.0, -50.0),
(".Lo", -40.0, -100.0)
)
co = GameLogic.getCurrentController()
obj = co.owner
act = co.actuators["LOD." + obj.name]
cam = GameLogic.getCurrentScene().active_camera
def Depth(pos, plane):
return pos[0]*plane[0] + pos[1]*plane[1] + pos[2]*plane[2] + plane[3]
# Depth is negative and decreasing further from the camera
depth = Depth(obj.position, cam.world_to_camera[2])
newmesh = None
curmesh = None
# Find the lowest detail mesh for depth
for mesh in meshes:
if depth < mesh[1] and depth > mesh[2]:
newmesh = mesh
if "ME" + obj.name + mesh[0] == act.getMesh():
curmesh = mesh
if newmesh != None and "ME" + obj.name + newmesh[0] != act.getMesh():
# The mesh is a different mesh - switch it.
# Check the current mesh is not a better fit.
if curmesh == None or curmesh[1] < depth or curmesh[2] > depth:
act.mesh = obj.getName() + newmesh[0]
GameLogic.addActiveActuator(act, True)
.. attribute:: mesh
:class:`MeshProxy` or the name of the mesh that will replace the current one.
Set to None to disable actuator.
:type: :class:`MeshProxy` or None if no mesh is set
.. attribute:: useDisplayMesh
when true the displayed mesh is replaced.
:type: boolean
.. attribute:: usePhysicsMesh
when true the physics mesh is replaced.
:type: boolean
.. method:: instantReplaceMesh()
Immediately replace mesh without delay.
.. class:: KX_Scene(PyObjectPlus)
An active scene that gives access to objects, cameras, lights and scene attributes.
The activity culling stuff is supposed to disable logic bricks when their owner gets too far
from the active camera. It was taken from some code lurking at the back of KX_Scene - who knows
what it does!
.. code-block:: python
import GameLogic
# get the scene
scene = GameLogic.getCurrentScene()
# print all the objects in the scene
for obj in scene.objects:
print obj.name
# get an object named 'Cube'
obj = scene.objects["Cube"]
# get the first object in the scene.
obj = scene.objects[0]
.. code-block:: python
# Get the depth of an object in the camera view.
import GameLogic
obj = GameLogic.getCurrentController().owner
cam = GameLogic.getCurrentScene().active_camera
# Depth is negative and decreasing further from the camera
depth = obj.position[0]*cam.world_to_camera[2][0] + obj.position[1]*cam.world_to_camera[2][1] + obj.position[2]*cam.world_to_camera[2][2] + cam.world_to_camera[2][3]
@bug: All attributes are read only at the moment.
.. attribute:: name
The scene's name, (read-only).
:type: string
.. attribute:: objects
A list of objects in the scene, (read-only).
:type: :class:`CListValue` of :class:`KX_GameObject`
.. attribute:: objectsInactive
A list of objects on background layers (used for the addObject actuator), (read-only).
:type: :class:`CListValue` of :class:`KX_GameObject`
.. attribute:: lights
A list of lights in the scene, (read-only).
:type: :class:`CListValue` of :class:`KX_LightObject`
.. attribute:: cameras
A list of cameras in the scene, (read-only).
:type: :class:`CListValue` of :class:`KX_Camera`
.. attribute:: active_camera
The current active camera.
:type: :class:`KX_Camera`
.. note::
This can be set directly from python to avoid using the :class:`KX_SceneActuator`.
.. attribute:: suspended
True if the scene is suspended, (read-only).
:type: boolean
.. attribute:: activity_culling
True if the scene is activity culling.
:type: boolean
.. attribute:: activity_culling_radius
The distance outside which to do activity culling. Measured in manhattan distance.
:type: float
.. attribute:: dbvt_culling
True when Dynamic Bounding box Volume Tree is set (read-only).
:type: boolean
.. attribute:: pre_draw
A list of callables to be run before the render step.
:type: list
.. attribute:: post_draw
A list of callables to be run after the render step.
:type: list
.. method:: addObject(object, other, time=0)
Adds an object to the scene like the Add Object Actuator would.
:arg object: The object to add
:type object: :class:`KX_GameObject` or string
:arg other: The object's center to use when adding the object
:type other: :class:`KX_GameObject` or string
:arg time: The lifetime of the added object, in frames. A time of 0 means the object will last forever.
:type time: integer
:return: The newly added object.
:rtype: :class:`KX_GameObject`
.. method:: end()
Removes the scene from the game.
.. method:: restart()
Restarts the scene.
.. method:: replace(scene)
Replaces this scene with another one.
:arg scene: The name of the scene to replace this scene with.
:type scene: string
.. method:: suspend()
Suspends this scene.
.. method:: resume()
Resume this scene.
.. method:: get(key, default=None)
Return the value matching key, or the default value if its not found.
:return: The key value or a default.
.. class:: KX_SceneActuator(SCA_IActuator)
Scene Actuator logic brick.
.. warning::
Scene actuators that use a scene name will be ignored if at game start, the named scene doesn't exist or is empty
This will generate a warning in the console:
.. code-block:: none
Error: GameObject 'Name' has a SceneActuator 'ActuatorName' (SetScene) without scene
.. attribute:: scene
the name of the scene to change to/overlay/underlay/remove/suspend/resume.
:type: string
.. attribute:: camera
the camera to change to.
:type: :class:`KX_Camera` on read, string or :class:`KX_Camera` on write
.. note::
When setting the attribute, you can use either a :class:`KX_Camera` or the name of the camera.
.. attribute:: useRestart
Set flag to True to restart the sene.
:type: boolean
.. attribute:: mode
The mode of the actuator.
:type: integer from 0 to 5.
.. class:: KX_SoundActuator(SCA_IActuator)
Sound Actuator.
The :data:`startSound`, :data:`pauseSound` and :data:`stopSound` do not requirethe actuator to be activated - they act instantly provided that the actuator has been activated once at least.
.. attribute:: fileName
The filename of the sound this actuator plays.
:type: string
.. attribute:: volume
The volume (gain) of the sound.
:type: float
.. attribute:: pitch
The pitch of the sound.
:type: float
.. attribute:: rollOffFactor
The roll off factor. Rolloff defines the rate of attenuation as the sound gets further away.
:type: float
.. attribute:: looping
The loop mode of the actuator.
:type: integer
.. attribute:: position
The position of the sound as a list: [x, y, z].
:type: float array
.. attribute:: velocity
The velocity of the emitter as a list: [x, y, z]. The relative velocity to the observer determines the pitch. List of 3 floats: [x, y, z].
:type: float array
.. attribute:: orientation
The orientation of the sound. When setting the orientation you can also use quaternion [float, float, float, float] or euler angles [float, float, float].
:type: 3x3 matrix [[float]]
.. attribute:: mode
The operation mode of the actuator. Can be one of :ref:`these constants<logic-sound-actuator>`
:type: integer
.. class:: KX_StateActuator(SCA_IActuator)
State actuator changes the state mask of parent object.
.. attribute:: operation
Type of bit operation to be applied on object state mask.
You can use one of :ref:`these constants <state-actuator-operation>`
:type: integer
.. attribute:: mask
Value that defines the bits that will be modified by the operation.
The bits that are 1 in the mask will be updated in the object state.
The bits that are 0 are will be left unmodified expect for the Copy operation which copies the mask to the object state.
:type: integer
.. class:: KX_TrackToActuator(SCA_IActuator)
Edit Object actuator in Track To mode.
.. warning::
Track To Actuators will be ignored if at game start, the object to track to is invalid.
This will generate a warning in the console:
.. code-block:: none
GameObject 'Name' no object in EditObjectActuator 'ActuatorName'
.. attribute:: object
the object this actuator tracks.
:type: :class:`KX_GameObject` or None
.. attribute:: time
the time in frames with which to delay the tracking motion.
:type: integer
.. attribute:: use3D
the tracking motion to use 3D.
:type: boolean
.. class:: KX_VehicleWrapper(PyObjectPlus)
KX_VehicleWrapper
TODO - description
.. method:: addWheel(wheel, attachPos, attachDir, axleDir, suspensionRestLength, wheelRadius, hasSteering)
Add a wheel to the vehicle
:arg wheel: The object to use as a wheel.
:type wheel: :class:`KX_GameObject` or a KX_GameObject name
:arg attachPos: The position that this wheel will attach to.
:type attachPos: vector of 3 floats
:arg attachDir: The direction this wheel points.
:type attachDir: vector of 3 floats
:arg axleDir: The direction of this wheels axle.
:type axleDir: vector of 3 floats
:arg suspensionRestLength: TODO - Description
:type suspensionRestLength: float
:arg wheelRadius: The size of the wheel.
:type wheelRadius: float
.. method:: applyBraking(force, wheelIndex)
Apply a braking force to the specified wheel
:arg force: the brake force
:type force: float
:arg wheelIndex: index of the wheel where the force needs to be applied
:type wheelIndex: integer
.. method:: applyEngineForce(force, wheelIndex)
Apply an engine force to the specified wheel
:arg force: the engine force
:type force: float
:arg wheelIndex: index of the wheel where the force needs to be applied
:type wheelIndex: integer
.. method:: getConstraintId()
Get the constraint ID
:return: the constraint id
:rtype: integer
.. method:: getConstraintType()
Returns the constraint type.
:return: constraint type
:rtype: integer
.. method:: getNumWheels()
Returns the number of wheels.
:return: the number of wheels for this vehicle
:rtype: integer
.. method:: getWheelOrientationQuaternion(wheelIndex)
Returns the wheel orientation as a quaternion.
:arg wheelIndex: the wheel index
:type wheelIndex: integer
:return: TODO Description
:rtype: TODO - type should be quat as per method name but from the code it looks like a matrix
.. method:: getWheelPosition(wheelIndex)
Returns the position of the specified wheel
:arg wheelIndex: the wheel index
:type wheelIndex: integer
:return: position vector
:rtype: list[x, y, z]
.. method:: getWheelRotation(wheelIndex)
Returns the rotation of the specified wheel
:arg wheelIndex: the wheel index
:type wheelIndex: integer
:return: the wheel rotation
:rtype: float
.. method:: setRollInfluence(rollInfluece, wheelIndex)
Set the specified wheel's roll influence.
The higher the roll influence the more the vehicle will tend to roll over in corners.
:arg rollInfluece: the wheel roll influence
:type rollInfluece: float
:arg wheelIndex: the wheel index
:type wheelIndex: integer
.. method:: setSteeringValue(steering, wheelIndex)
Set the specified wheel's steering
:arg steering: the wheel steering
:type steering: float
:arg wheelIndex: the wheel index
:type wheelIndex: integer
.. method:: setSuspensionCompression(compression, wheelIndex)
Set the specified wheel's compression
:arg compression: the wheel compression
:type compression: float
:arg wheelIndex: the wheel index
:type wheelIndex: integer
.. method:: setSuspensionDamping(damping, wheelIndex)
Set the specified wheel's damping
:arg damping: the wheel damping
:type damping: float
:arg wheelIndex: the wheel index
:type wheelIndex: integer
.. method:: setSuspensionStiffness(stiffness, wheelIndex)
Set the specified wheel's stiffness
:arg stiffness: the wheel stiffness
:type stiffness: float
:arg wheelIndex: the wheel index
:type wheelIndex: integer
.. method:: setTyreFriction(friction, wheelIndex)
Set the specified wheel's tyre friction
:arg friction: the tyre friction
:type friction: float
:arg wheelIndex: the wheel index
:type wheelIndex: integer
.. class:: KX_VertexProxy(SCA_IObject)
A vertex holds position, UV, colour and normal information.
Note:
The physics simulation is NOT currently updated - physics will not respond
to changes in the vertex position.
.. attribute:: XYZ
The position of the vertex.
:type: list [x, y, z]
.. attribute:: UV
The texture coordinates of the vertex.
:type: list [u, v]
.. attribute:: normal
The normal of the vertex.
:type: list [nx, ny, nz]
.. attribute:: colour
The colour of the vertex.
:type: list [r, g, b, a]
Black = [0.0, 0.0, 0.0, 1.0], White = [1.0, 1.0, 1.0, 1.0]
.. attribute:: color
Synonym for colour.
.. attribute:: x
The x coordinate of the vertex.
:type: float
.. attribute:: y
The y coordinate of the vertex.
:type: float
.. attribute:: z
The z coordinate of the vertex.
:type: float
.. attribute:: u
The u texture coordinate of the vertex.
:type: float
.. attribute:: v
The v texture coordinate of the vertex.
:type: float
.. attribute:: u2
The second u texture coordinate of the vertex.
:type: float
.. attribute:: v2
The second v texture coordinate of the vertex.
:type: float
.. attribute:: r
The red component of the vertex colour. 0.0 <= r <= 1.0.
:type: float
.. attribute:: g
The green component of the vertex colour. 0.0 <= g <= 1.0.
:type: float
.. attribute:: b
The blue component of the vertex colour. 0.0 <= b <= 1.0.
:type: float
.. attribute:: a
The alpha component of the vertex colour. 0.0 <= a <= 1.0.
:type: float
.. method:: getXYZ()
Gets the position of this vertex.
:return: this vertexes position in local coordinates.
:rtype: list [x, y, z]
.. method:: setXYZ(pos)
Sets the position of this vertex.
:type: list [x, y, z]
:arg pos: the new position for this vertex in local coordinates.
.. method:: getUV()
Gets the UV (texture) coordinates of this vertex.
:return: this vertexes UV (texture) coordinates.
:rtype: list [u, v]
.. method:: setUV(uv)
Sets the UV (texture) coordinates of this vertex.
:type: list [u, v]
.. method:: getUV2()
Gets the 2nd UV (texture) coordinates of this vertex.
:return: this vertexes UV (texture) coordinates.
:rtype: list [u, v]
.. method:: setUV2(uv, unit)
Sets the 2nd UV (texture) coordinates of this vertex.
:type: list [u, v]
:arg unit: optional argument, FLAT==1, SECOND_UV==2, defaults to SECOND_UV
:arg unit: integer
.. method:: getRGBA()
Gets the colour of this vertex.
The colour is represented as four bytes packed into an integer value. The colour is
packed as RGBA.
Since Python offers no way to get each byte without shifting, you must use the struct module to
access colour in an machine independent way.
Because of this, it is suggested you use the r, g, b and a attributes or the colour attribute instead.
.. code-block:: python
import struct;
col = struct.unpack('4B', struct.pack('I', v.getRGBA()))
# col = (r, g, b, a)
# black = ( 0, 0, 0, 255)
# white = (255, 255, 255, 255)
:return: packed colour. 4 byte integer with one byte per colour channel in RGBA format.
:rtype: integer
.. method:: setRGBA(col)
Sets the colour of this vertex.
See getRGBA() for the format of col, and its relevant problems. Use the r, g, b and a attributes
or the colour attribute instead.
setRGBA() also accepts a four component list as argument col. The list represents the colour as [r, g, b, a]
with black = [0.0, 0.0, 0.0, 1.0] and white = [1.0, 1.0, 1.0, 1.0]
.. code-block:: python
v.setRGBA(0xff0000ff) # Red
v.setRGBA(0xff00ff00) # Green on little endian, transparent purple on big endian
v.setRGBA([1.0, 0.0, 0.0, 1.0]) # Red
v.setRGBA([0.0, 1.0, 0.0, 1.0]) # Green on all platforms.
:arg col: the new colour of this vertex in packed RGBA format.
:type col: integer or list [r, g, b, a]
.. method:: getNormal()
Gets the normal vector of this vertex.
:return: normalised normal vector.
:rtype: list [nx, ny, nz]
.. method:: setNormal(normal)
Sets the normal vector of this vertex.
:type: sequence of floats [r, g, b]
:arg normal: the new normal of this vertex.
.. class:: KX_VisibilityActuator(SCA_IActuator)
Visibility Actuator.
.. attribute:: visibility
whether the actuator makes its parent object visible or invisible.
:type: boolean
.. attribute:: useOcclusion
whether the actuator makes its parent object an occluder or not.
:type: boolean
.. attribute:: useRecursion
whether the visibility/occlusion should be propagated to all children of the object.
:type: boolean
.. class:: SCA_2DFilterActuator(SCA_IActuator)
Create, enable and disable 2D filters
The following properties don't have an immediate effect.
You must active the actuator to get the result.
The actuator is not persistent: it automatically stops itself after setting up the filter
but the filter remains active. To stop a filter you must activate the actuator with 'type'
set to :data:`~bge.logic.RAS_2DFILTER_DISABLED` or :data:`~bge.logic.RAS_2DFILTER_NOFILTER`.
.. attribute:: shaderText
shader source code for custom shader.
:type: string
.. attribute:: disableMotionBlur
action on motion blur: 0=enable, 1=disable.
:type: integer
.. attribute:: mode
Type of 2D filter, use one of :ref:`these constants <Two-D-FilterActuator-mode>`
:type: integer
.. attribute:: passNumber
order number of filter in the stack of 2D filters. Filters are executed in increasing order of passNb.
Only be one filter can be defined per passNb.
:type: integer (0-100)
.. attribute:: value
argument for motion blur filter.
:type: float (0.0-100.0)
.. class:: SCA_ANDController(SCA_IController)
An AND controller activates only when all linked sensors are activated.
There are no special python methods for this controller.
.. class:: SCA_ActuatorSensor(SCA_ISensor)
Actuator sensor detect change in actuator state of the parent object.
It generates a positive pulse if the corresponding actuator is activated
and a negative pulse if the actuator is deactivated.
.. attribute:: actuator
the name of the actuator that the sensor is monitoring.
:type: string
.. class:: SCA_AlwaysSensor(SCA_ISensor)
This sensor is always activated.
.. class:: SCA_DelaySensor(SCA_ISensor)
The Delay sensor generates positive and negative triggers at precise time,
expressed in number of frames. The delay parameter defines the length of the initial OFF period. A positive trigger is generated at the end of this period.
The duration parameter defines the length of the ON period following the OFF period.
There is a negative trigger at the end of the ON period. If duration is 0, the sensor stays ON and there is no negative trigger.
The sensor runs the OFF-ON cycle once unless the repeat option is set: the OFF-ON cycle repeats indefinately (or the OFF cycle if duration is 0).
Use :class:`SCA_ISensor.reset` at any time to restart sensor.
.. attribute:: delay
length of the initial OFF period as number of frame, 0 for immediate trigger.
:type: integer.
.. attribute:: duration
length of the ON period in number of frame after the initial OFF period.
If duration is greater than 0, a negative trigger is sent at the end of the ON pulse.
:type: integer
.. attribute:: repeat
1 if the OFF-ON cycle should be repeated indefinately, 0 if it should run once.
:type: integer
.. class:: SCA_JoystickSensor(SCA_ISensor)
This sensor detects player joystick events.
.. attribute:: axisValues
The state of the joysticks axis as a list of values :data:`numAxis` long. (read-only).
:type: list of ints.
Each spesifying the value of an axis between -32767 and 32767 depending on how far the axis is pushed, 0 for nothing.
The first 2 values are used by most joysticks and gamepads for directional control. 3rd and 4th values are only on some joysticks and can be used for arbitary controls.
* left:[-32767, 0, ...]
* right:[32767, 0, ...]
* up:[0, -32767, ...]
* down:[0, 32767, ...]
.. attribute:: axisSingle
like :data:`axisValues` but returns a single axis value that is set by the sensor. (read-only).
:type: integer
.. note::
Only use this for "Single Axis" type sensors otherwise it will raise an error.
.. attribute:: hatValues
The state of the joysticks hats as a list of values :data:`numHats` long. (read-only).
:type: list of ints
Each spesifying the direction of the hat from 1 to 12, 0 when inactive.
Hat directions are as follows...
* 0:None
* 1:Up
* 2:Right
* 4:Down
* 8:Left
* 3:Up - Right
* 6:Down - Right
* 12:Down - Left
* 9:Up - Left
.. attribute:: hatSingle
Like :data:`hatValues` but returns a single hat direction value that is set by the sensor. (read-only).
:type: integer
.. attribute:: numAxis
The number of axes for the joystick at this index. (read-only).
:type: integer
.. attribute:: numButtons
The number of buttons for the joystick at this index. (read-only).
:type: integer
.. attribute:: numHats
The number of hats for the joystick at this index. (read-only).
:type: integer
.. attribute:: connected
True if a joystick is connected at this joysticks index. (read-only).
:type: boolean
.. attribute:: index
The joystick index to use (from 0 to 7). The first joystick is always 0.
:type: integer
.. attribute:: threshold
Axis threshold. Joystick axis motion below this threshold wont trigger an event. Use values between (0 and 32767), lower values are more sensitive.
:type: integer
.. attribute:: button
The button index the sensor reacts to (first button = 0). When the "All Events" toggle is set, this option has no effect.
:type: integer
.. attribute:: axis
The axis this sensor reacts to, as a list of two values [axisIndex, axisDirection]
* axisIndex: the axis index to use when detecting axis movement, 1=primary directional control, 2=secondary directional control.
* axisDirection: 0=right, 1=up, 2=left, 3=down.
:type: [integer, integer]
.. attribute:: hat
The hat the sensor reacts to, as a list of two values: [hatIndex, hatDirection]
* hatIndex: the hat index to use when detecting hat movement, 1=primary hat, 2=secondary hat (4 max).
* hatDirection: 1-12.
:type: [integer, integer]
.. method:: getButtonActiveList()
:return: A list containing the indicies of the currently pressed buttons.
:rtype: list
.. method:: getButtonStatus(buttonIndex)
:arg buttonIndex: the button index, 0=first button
:type buttonIndex: integer
:return: The current pressed state of the specified button.
:rtype: boolean
.. class:: SCA_KeyboardSensor(SCA_ISensor)
A keyboard sensor detects player key presses.
See module :mod:`bge.keys` for keycode values.
.. attribute:: key
The key code this sensor is looking for.
:type: keycode from :mod:`bge.keys` module
.. attribute:: hold1
The key code for the first modifier this sensor is looking for.
:type: keycode from :mod:`bge.keys` module
.. attribute:: hold2
The key code for the second modifier this sensor is looking for.
:type: keycode from :mod:`bge.keys` module
.. attribute:: toggleProperty
The name of the property that indicates whether or not to log keystrokes as a string.
:type: string
.. attribute:: targetProperty
The name of the property that receives keystrokes in case in case a string is logged.
:type: string
.. attribute:: useAllKeys
Flag to determine whether or not to accept all keys.
:type: boolean
.. attribute:: events
a list of pressed keys that have either been pressed, or just released, or are active this frame. (read-only).
:type: list [[:ref:`keycode<keyboard-keys>`, :ref:`status<input-status>`], ...]
.. method:: getKeyStatus(keycode)
Get the status of a key.
:arg keycode: The code that represents the key you want to get the state of, use one of :ref:`these constants<keyboard-keys>`
:type keycode: integer
:return: The state of the given key, can be one of :ref:`these constants<input-status>`
:rtype: int
.. class:: SCA_NANDController(SCA_IController)
An NAND controller activates when all linked sensors are not active.
There are no special python methods for this controller.
.. class:: SCA_NORController(SCA_IController)
An NOR controller activates only when all linked sensors are de-activated.
There are no special python methods for this controller.
.. class:: SCA_ORController(SCA_IController)
An OR controller activates when any connected sensor activates.
There are no special python methods for this controller.
.. class:: SCA_PropertyActuator(SCA_IActuator)
Property Actuator
.. attribute:: propName
the property on which to operate.
:type: string
.. attribute:: value
the value with which the actuator operates.
:type: string
.. attribute:: mode
TODO - add constants to game logic dict!.
:type: integer
.. class:: SCA_PropertySensor(SCA_ISensor)
Activates when the game object property matches.
.. attribute:: mode
Type of check on the property. Can be one of :ref:`these constants <logic-property-sensor>`
:type: integer.
.. attribute:: propName
the property the sensor operates.
:type: string
.. attribute:: value
the value with which the sensor compares to the value of the property.
:type: string
.. attribute:: min
the minimum value of the range used to evaluate the property when in interval mode.
:type: string
.. attribute:: max
the maximum value of the range used to evaluate the property when in interval mode.
:type: string
.. class:: SCA_PythonController(SCA_IController)
A Python controller uses a Python script to activate it's actuators,
based on it's sensors.
.. attribute:: script
The value of this variable depends on the execution methid.
* When 'Script' execution mode is set this value contains the entire python script as a single string (not the script name as you might expect) which can be modified to run different scripts.
* When 'Module' execution mode is set this value will contain a single line string - module name and function "module.func" or "package.modile.func" where the module names are python textblocks or external scripts.
:type: string
.. note::
Once this is set the script name given for warnings will remain unchanged.
.. attribute:: mode
the execution mode for this controller (read-only).
* Script: 0, Execite the :data:`script` as a python code.
* Module: 1, Execite the :data:`script` as a module and function.
:type: integer
.. method:: activate(actuator)
Activates an actuator attached to this controller.
:arg actuator: The actuator to operate on.
:type actuator: actuator or the actuator name as a string
.. method:: deactivate(actuator)
Deactivates an actuator attached to this controller.
:arg actuator: The actuator to operate on.
:type actuator: actuator or the actuator name as a string
.. class:: SCA_RandomActuator(SCA_IActuator)
Random Actuator
.. attribute:: seed
Seed of the random number generator.
:type: integer.
Equal seeds produce equal series. If the seed is 0, the generator will produce the same value on every call.
.. attribute:: para1
the first parameter of the active distribution.
:type: float, read-only.
Refer to the documentation of the generator types for the meaning of this value.
.. attribute:: para2
the second parameter of the active distribution.
:type: float, read-only
Refer to the documentation of the generator types for the meaning of this value.
.. attribute:: distribution
Distribution type. (read-only). Can be one of :ref:`these constants <logic-random-distributions>`
:type: integer
.. attribute:: propName
the name of the property to set with the random value.
:type: string
If the generator and property types do not match, the assignment is ignored.
.. method:: setBoolConst(value)
Sets this generator to produce a constant boolean value.
:arg value: The value to return.
:type value: boolean
.. method:: setBoolUniform()
Sets this generator to produce a uniform boolean distribution.
The generator will generate True or False with 50% chance.
.. method:: setBoolBernouilli(value)
Sets this generator to produce a Bernouilli distribution.
:arg value: Specifies the proportion of False values to produce.
* 0.0: Always generate True
* 1.0: Always generate False
:type value: float
.. method:: setIntConst(value)
Sets this generator to always produce the given value.
:arg value: the value this generator produces.
:type value: integer
.. method:: setIntUniform(lower_bound, upper_bound)
Sets this generator to produce a random value between the given lower and
upper bounds (inclusive).
:type lower_bound: integer
:type upper_bound: integer
.. method:: setIntPoisson(value)
Generate a Poisson-distributed number.
This performs a series of Bernouilli tests with parameter value.
It returns the number of tries needed to achieve succes.
:type value: float
.. method:: setFloatConst(value)
Always generate the given value.
:type value: float
.. method:: setFloatUniform(lower_bound, upper_bound)
Generates a random float between lower_bound and upper_bound with a
uniform distribution.
:type lower_bound: float
:type upper_bound: float
.. method:: setFloatNormal(mean, standard_deviation)
Generates a random float from the given normal distribution.
:arg mean: The mean (average) value of the generated numbers
:type mean: float
:arg standard_deviation: The standard deviation of the generated numbers.
:type standard_deviation: float
.. method:: setFloatNegativeExponential(half_life)
Generate negative-exponentially distributed numbers.
The half-life 'time' is characterized by half_life.
:type half_life: float
.. class:: SCA_RandomSensor(SCA_ISensor)
This sensor activates randomly.
.. attribute:: lastDraw
The seed of the random number generator.
:type: integer
.. attribute:: seed
The seed of the random number generator.
:type: integer
.. method:: setSeed(seed)
Sets the seed of the random number generator.
If the seed is 0, the generator will produce the same value on every call.
:type seed: integer
.. method:: getSeed()
:return: The initial seed of the generator. Equal seeds produce equal random series.
:rtype: integer
.. method:: getLastDraw()
:return: The last random number generated.
:rtype: integer
.. class:: SCA_XNORController(SCA_IController)
An XNOR controller activates when all linked sensors are the same (activated or inative).
There are no special python methods for this controller.
.. class:: SCA_XORController(SCA_IController)
An XOR controller activates when there is the input is mixed, but not when all are on or off.
There are no special python methods for this controller.
.. class:: KX_Camera(KX_GameObject)
A Camera object.
.. data:: INSIDE
See :data:`sphereInsideFrustum` and :data:`boxInsideFrustum`
.. data:: INTERSECT
See :data:`sphereInsideFrustum` and :data:`boxInsideFrustum`
.. data:: OUTSIDE
See :data:`sphereInsideFrustum` and :data:`boxInsideFrustum`
.. attribute:: lens
The camera's lens value.
:type: float
.. attribute:: ortho_scale
The camera's view scale when in orthographic mode.
:type: float
.. attribute:: near
The camera's near clip distance.
:type: float
.. attribute:: far
The camera's far clip distance.
:type: float
.. attribute:: perspective
True if this camera has a perspective transform, False for an orthographic projection.
:type: boolean
.. attribute:: frustum_culling
True if this camera is frustum culling.
:type: boolean
.. attribute:: projection_matrix
This camera's 4x4 projection matrix.
:type: 4x4 Matrix [[float]]
.. attribute:: modelview_matrix
This camera's 4x4 model view matrix. (read-only).
:type: 4x4 Matrix [[float]]
.. note::
This matrix is regenerated every frame from the camera's position and orientation.
.. attribute:: camera_to_world
This camera's camera to world transform. (read-only).
:type: 4x4 Matrix [[float]]
.. note::
This matrix is regenerated every frame from the camera's position and orientation.
.. attribute:: world_to_camera
This camera's world to camera transform. (read-only).
:type: 4x4 Matrix [[float]]
.. note::
Regenerated every frame from the camera's position and orientation.
.. note::
This is camera_to_world inverted.
.. attribute:: useViewport
True when the camera is used as a viewport, set True to enable a viewport for this camera.
:type: boolean
.. method:: sphereInsideFrustum(centre, radius)
Tests the given sphere against the view frustum.
:arg centre: The centre of the sphere (in world coordinates.)
:type centre: list [x, y, z]
:arg radius: the radius of the sphere
:type radius: float
:return: :data:`~bge.types.KX_Camera.INSIDE`, :data:`~bge.types.KX_Camera.OUTSIDE` or :data:`~bge.types.KX_Camera.INTERSECT`
:rtype: integer
.. note::
When the camera is first initialized the result will be invalid because the projection matrix has not been set.
.. code-block:: python
import GameLogic
co = GameLogic.getCurrentController()
cam = co.owner
# A sphere of radius 4.0 located at [x, y, z] = [1.0, 1.0, 1.0]
if (cam.sphereInsideFrustum([1.0, 1.0, 1.0], 4) != cam.OUTSIDE):
# Sphere is inside frustum !
# Do something useful !
else:
# Sphere is outside frustum
.. method:: boxInsideFrustum(box)
Tests the given box against the view frustum.
:arg box: Eight (8) corner points of the box (in world coordinates.)
:type box: list of lists
:return: :data:`~bge.types.KX_Camera.INSIDE`, :data:`~bge.types.KX_Camera.OUTSIDE` or :data:`~bge.types.KX_Camera.INTERSECT`
.. note::
When the camera is first initialized the result will be invalid because the projection matrix has not been set.
.. code-block:: python
import GameLogic
co = GameLogic.getCurrentController()
cam = co.owner
# Box to test...
box = []
box.append([-1.0, -1.0, -1.0])
box.append([-1.0, -1.0, 1.0])
box.append([-1.0, 1.0, -1.0])
box.append([-1.0, 1.0, 1.0])
box.append([ 1.0, -1.0, -1.0])
box.append([ 1.0, -1.0, 1.0])
box.append([ 1.0, 1.0, -1.0])
box.append([ 1.0, 1.0, 1.0])
if (cam.boxInsideFrustum(box) != cam.OUTSIDE):
# Box is inside/intersects frustum !
# Do something useful !
else:
# Box is outside the frustum !
.. method:: pointInsideFrustum(point)
Tests the given point against the view frustum.
:arg point: The point to test (in world coordinates.)
:type point: 3D Vector
:return: True if the given point is inside this camera's viewing frustum.
:rtype: boolean
.. note::
When the camera is first initialized the result will be invalid because the projection matrix has not been set.
.. code-block:: python
import GameLogic
co = GameLogic.getCurrentController()
cam = co.owner
# Test point [0.0, 0.0, 0.0]
if (cam.pointInsideFrustum([0.0, 0.0, 0.0])):
# Point is inside frustum !
# Do something useful !
else:
# Box is outside the frustum !
.. method:: getCameraToWorld()
Returns the camera-to-world transform.
:return: the camera-to-world transform matrix.
:rtype: matrix (4x4 list)
.. method:: getWorldToCamera()
Returns the world-to-camera transform.
This returns the inverse matrix of getCameraToWorld().
:return: the world-to-camera transform matrix.
:rtype: matrix (4x4 list)
.. method:: setOnTop()
Set this cameras viewport ontop of all other viewport.
.. method:: setViewport(left, bottom, right, top)
Sets the region of this viewport on the screen in pixels.
Use :data:`bge.render.getWindowHeight` and :data:`bge.render.getWindowWidth` to calculate values relative to the entire display.
:arg left: left pixel coordinate of this viewport
:type left: integer
:arg bottom: bottom pixel coordinate of this viewport
:type bottom: integer
:arg right: right pixel coordinate of this viewport
:type right: integer
:arg top: top pixel coordinate of this viewport
:type top: integer
.. method:: getScreenPosition(object)
Gets the position of an object projected on screen space.
.. code-block:: python
# For an object in the middle of the screen, coord = [0.5, 0.5]
coord = camera.getScreenPosition(object)
:arg object: object name or list [x, y, z]
:type object: :class:`KX_GameObject` or 3D Vector
:return: the object's position in screen coordinates.
:rtype: list [x, y]
.. method:: getScreenVect(x, y)
Gets the vector from the camera position in the screen coordinate direction.
:arg x: X Axis
:type x: float
:arg y: Y Axis
:type y: float
:rtype: 3D Vector
:return: The vector from screen coordinate.
.. code-block:: python
# Gets the vector of the camera front direction:
m_vect = camera.getScreenVect(0.5, 0.5)
.. method:: getScreenRay(x, y, dist=inf, property=None)
Look towards a screen coordinate (x, y) and find first object hit within dist that matches prop.
The ray is similar to KX_GameObject->rayCastTo.
:arg x: X Axis
:type x: float
:arg y: Y Axis
:type y: float
:arg dist: max distance to look (can be negative => look behind); 0 or omitted => detect up to other
:type dist: float
:arg property: property name that object must have; can be omitted => detect any object
:type property: string
:rtype: :class:`KX_GameObject`
:return: the first object hit or None if no object or object does not match prop
.. code-block:: python
# Gets an object with a property "wall" in front of the camera within a distance of 100:
target = camera.getScreenRay(0.5, 0.5, 100, "wall")
.. class:: BL_ArmatureObject(KX_GameObject)
An armature object.
.. attribute:: constraints
The list of armature constraint defined on this armature.
Elements of the list can be accessed by index or string.
The key format for string access is '<bone_name>:<constraint_name>'.
:type: list of :class:`BL_ArmatureConstraint`
.. attribute:: channels
The list of armature channels.
Elements of the list can be accessed by index or name the bone.
:type: list of :class:`BL_ArmatureChannel`
.. method:: update()
Ensures that the armature will be updated on next graphic frame.
This action is unecessary if a KX_ArmatureActuator with mode run is active
or if an action is playing. Use this function in other cases. It must be called
on each frame to ensure that the armature is updated continously.
.. class:: BL_ArmatureActuator(SCA_IActuator)
Armature Actuators change constraint condition on armatures.
.. _armatureactuator-constants-type:
Constants related to :data:`~bge.types.BL_ArmatureActuator.type`
.. data:: KX_ACT_ARMATURE_RUN
Just make sure the armature will be updated on the next graphic frame. This is the only persistent mode of the actuator: it executes automatically once per frame until stopped by a controller
:value: 0
.. data:: KX_ACT_ARMATURE_ENABLE
Enable the constraint.
:value: 1
.. data:: KX_ACT_ARMATURE_DISABLE
Disable the constraint (runtime constraint values are not updated).
:value: 2
.. data:: KX_ACT_ARMATURE_SETTARGET
Change target and subtarget of constraint.
:value: 3
.. data:: KX_ACT_ARMATURE_SETWEIGHT
Change weight of (only for IK constraint).
:value: 4
.. attribute:: type
The type of action that the actuator executes when it is active.
Can be one of :ref:`these constants <armatureactuator-constants-type>`
:type: integer
.. attribute:: constraint
The constraint object this actuator is controlling.
:type: :class:`BL_ArmatureConstraint`
.. attribute:: target
The object that this actuator will set as primary target to the constraint it controls.
:type: :class:`KX_GameObject`
.. attribute:: subtarget
The object that this actuator will set as secondary target to the constraint it controls.
:type: :class:`KX_GameObject`.
.. note::
Currently, the only secondary target is the pole target for IK constraint.
.. attribute:: weight
The weight this actuator will set on the constraint it controls.
:type: float.
.. note::
Currently only the IK constraint has a weight. It must be a value between 0 and 1.
.. note::
A weight of 0 disables a constraint while still updating constraint runtime values (see :class:`BL_ArmatureConstraint`)
.. class:: KX_ArmatureSensor(SCA_ISensor)
Armature sensor detect conditions on armatures.
.. _armaturesensor-type:
Constants related to :data:`type`
.. data:: KX_ARMSENSOR_STATE_CHANGED
Detect that the constraint is changing state (active/inactive)
:value: 0
.. data:: KX_ARMSENSOR_LIN_ERROR_BELOW
Detect that the constraint linear error is above a threshold
:value: 1
.. data:: KX_ARMSENSOR_LIN_ERROR_ABOVE
Detect that the constraint linear error is below a threshold
:value: 2
.. data:: KX_ARMSENSOR_ROT_ERROR_BELOW
Detect that the constraint rotation error is above a threshold
:value: 3
.. data:: KX_ARMSENSOR_ROT_ERROR_ABOVE
Detect that the constraint rotation error is below a threshold
:value: 4
.. attribute:: type
The type of measurement that the sensor make when it is active.
Can be one of :ref:`these constants <armaturesensor-type>`
:type: integer.
.. attribute:: constraint
The constraint object this sensor is watching.
:type: :class:`BL_ArmatureConstraint`
.. attribute:: value
The threshold used in the comparison with the constraint error
The linear error is only updated on CopyPose/Distance IK constraint with iTaSC solver
The rotation error is only updated on CopyPose+rotation IK constraint with iTaSC solver
The linear error on CopyPose is always >= 0: it is the norm of the distance between the target and the bone
The rotation error on CopyPose is always >= 0: it is the norm of the equivalent rotation vector between the bone and the target orientations
The linear error on Distance can be positive if the distance between the bone and the target is greater than the desired distance, and negative if the distance is smaller.
:type: float
.. class:: BL_ArmatureConstraint(PyObjectPlus)
Proxy to Armature Constraint. Allows to change constraint on the fly.
Obtained through :class:`BL_ArmatureObject`.constraints.
.. note::
Not all armature constraints are supported in the GE.
.. _armatureconstraint-constants-type:
Constants related to :data:`type`
.. data:: CONSTRAINT_TYPE_TRACKTO
.. data:: CONSTRAINT_TYPE_KINEMATIC
.. data:: CONSTRAINT_TYPE_ROTLIKE
.. data:: CONSTRAINT_TYPE_LOCLIKE
.. data:: CONSTRAINT_TYPE_MINMAX
.. data:: CONSTRAINT_TYPE_SIZELIKE
.. data:: CONSTRAINT_TYPE_LOCKTRACK
.. data:: CONSTRAINT_TYPE_STRETCHTO
.. data:: CONSTRAINT_TYPE_CLAMPTO
.. data:: CONSTRAINT_TYPE_TRANSFORM
.. data:: CONSTRAINT_TYPE_DISTLIMIT
.. _armatureconstraint-constants-ik-type:
Constants related to :data:`ik_type`
.. data:: CONSTRAINT_IK_COPYPOSE
constraint is trying to match the position and eventually the rotation of the target.
:value: 0
.. data:: CONSTRAINT_IK_DISTANCE
Constraint is maintaining a certain distance to target subject to ik_mode
:value: 1
.. _armatureconstraint-constants-ik-flag:
Constants related to :data:`ik_flag`
.. data:: CONSTRAINT_IK_FLAG_TIP
Set when the constraint operates on the head of the bone and not the tail
:value: 1
.. data:: CONSTRAINT_IK_FLAG_ROT
Set when the constraint tries to match the orientation of the target
:value: 2
.. data:: CONSTRAINT_IK_FLAG_STRETCH
Set when the armature is allowed to stretch (only the bones with stretch factor > 0.0)
:value: 16
.. data:: CONSTRAINT_IK_FLAG_POS
Set when the constraint tries to match the position of the target.
:value: 32
.. _armatureconstraint-constants-ik-mode:
Constants related to :data:`ik_mode`
.. data:: CONSTRAINT_IK_MODE_INSIDE
The constraint tries to keep the bone within ik_dist of target
:value: 0
.. data:: CONSTRAINT_IK_MODE_OUTSIDE
The constraint tries to keep the bone outside ik_dist of the target
:value: 1
.. data:: CONSTRAINT_IK_MODE_ONSURFACE
The constraint tries to keep the bone exactly at ik_dist of the target.
:value: 2
.. attribute:: type
Type of constraint, (read-only).
Use one of :ref:`these constants<armatureconstraint-constants-type>`.
:type: integer, one of CONSTRAINT_TYPE_* constants
.. attribute:: name
Name of constraint constructed as <bone_name>:<constraint_name>. constraints list.
:type: string
This name is also the key subscript on :class:`BL_ArmatureObject`.
.. attribute:: enforce
fraction of constraint effect that is enforced. Between 0 and 1.
:type: float
.. attribute:: headtail
Position of target between head and tail of the target bone: 0=head, 1=tail.
:type: float.
.. note::
Only used if the target is a bone (i.e target object is an armature.
.. attribute:: lin_error
runtime linear error (in Blender units) on constraint at the current frame.
This is a runtime value updated on each frame by the IK solver. Only available on IK constraint and iTaSC solver.
:type: float
.. attribute:: rot_error
Runtime rotation error (in radiant) on constraint at the current frame.
:type: float.
This is a runtime value updated on each frame by the IK solver. Only available on IK constraint and iTaSC solver.
It is only set if the constraint has a rotation part, for example, a CopyPose+Rotation IK constraint.
.. attribute:: target
Primary target object for the constraint. The position of this object in the GE will be used as target for the constraint.
:type: :class:`KX_GameObject`.
.. attribute:: subtarget
Secondary target object for the constraint. The position of this object in the GE will be used as secondary target for the constraint.
:type: :class:`KX_GameObject`.
Currently this is only used for pole target on IK constraint.
.. attribute:: active
True if the constraint is active.
:type: boolean
.. note::
An inactive constraint does not update lin_error and rot_error.
.. attribute:: ik_weight
Weight of the IK constraint between 0 and 1.
Only defined for IK constraint.
:type: float
.. attribute:: ik_type
Type of IK constraint, (read-only).
Use one of :ref:`these constants<armatureconstraint-constants-ik-type>`.
:type: integer.
.. attribute:: ik_flag
Combination of IK constraint option flags, read-only.
Use one of :ref:`these constants<armatureconstraint-constants-ik-flag>`.
:type: integer
.. attribute:: ik_dist
Distance the constraint is trying to maintain with target, only used when ik_type=CONSTRAINT_IK_DISTANCE.
:type: float
.. attribute:: ik_mode
Use one of :ref:`these constants<armatureconstraint-constants-ik-mode>`.
Additional mode for IK constraint. Currently only used for Distance constraint:
:type: integer
.. class:: BL_ArmatureChannel(PyObjectPlus)
Proxy to armature pose channel. Allows to read and set armature pose.
The attributes are identical to RNA attributes, but mostly in read-only mode.
See :data:`rotation_mode`
.. data:: PCHAN_ROT_QUAT
.. data:: PCHAN_ROT_XYZ
.. data:: PCHAN_ROT_XZY
.. data:: PCHAN_ROT_YXZ
.. data:: PCHAN_ROT_YZX
.. data:: PCHAN_ROT_ZXY
.. data:: PCHAN_ROT_ZYX
.. attribute:: name
channel name (=bone name), read-only.
:type: string
.. attribute:: bone
return the bone object corresponding to this pose channel, read-only.
:type: :class:`BL_ArmatureBone`
.. attribute:: parent
return the parent channel object, None if root channel, read-only.
:type: :class:`BL_ArmatureChannel`
.. attribute:: has_ik
true if the bone is part of an active IK chain, read-only.
This flag is not set when an IK constraint is defined but not enabled (miss target information for example).
:type: boolean
.. attribute:: ik_dof_x
true if the bone is free to rotation in the X axis, read-only.
:type: boolean
.. attribute:: ik_dof_y
true if the bone is free to rotation in the Y axis, read-only.
:type: boolean
.. attribute:: ik_dof_z
true if the bone is free to rotation in the Z axis, read-only.
:type: boolean
.. attribute:: ik_limit_x
true if a limit is imposed on X rotation, read-only.
:type: boolean
.. attribute:: ik_limit_y
true if a limit is imposed on Y rotation, read-only.
:type: boolean
.. attribute:: ik_limit_z
true if a limit is imposed on Z rotation, read-only.
:type: boolean
.. attribute:: ik_rot_control
true if channel rotation should applied as IK constraint, read-only.
:type: boolean
.. attribute:: ik_lin_control
true if channel size should applied as IK constraint, read-only.
:type: boolean
.. attribute:: location
displacement of the bone head in armature local space, read-write.
:type: vector [X, Y, Z].
.. note::
You can only move a bone if it is unconnected to its parent. An action playing on the armature may change the value. An IK chain does not update this value, see joint_rotation.
.. note::
Changing this field has no immediate effect, the pose is updated when the armature is updated during the graphic render (see :data:`BL_ArmatureObject.update`).
.. attribute:: scale
scale of the bone relative to its parent, read-write.
:type: vector [sizeX, sizeY, sizeZ].
.. note::
An action playing on the armature may change the value. An IK chain does not update this value, see joint_rotation.
.. note::
Changing this field has no immediate effect, the pose is updated when the armature is updated during the graphic render (see :data:`BL_ArmatureObject.update`)
.. attribute:: rotation_quaternion
rotation of the bone relative to its parent expressed as a quaternion, read-write.
:type: vector [qr, qi, qj, qk].
.. note::
This field is only used if rotation_mode is 0. An action playing on the armature may change the value. An IK chain does not update this value, see joint_rotation.
.. note::
Changing this field has no immediate effect, the pose is updated when the armature is updated during the graphic render (see :data:`BL_ArmatureObject.update`)
.. attribute:: rotation_euler
rotation of the bone relative to its parent expressed as a set of euler angles, read-write.
:type: vector [X, Y, Z].
.. note::
This field is only used if rotation_mode is > 0. You must always pass the angles in [X, Y, Z] order; the order of applying the angles to the bone depends on rotation_mode. An action playing on the armature may change this field. An IK chain does not update this value, see joint_rotation.
.. note::
Changing this field has no immediate effect, the pose is updated when the armature is updated during the graphic render (see :data:`BL_ArmatureObject.update`)
.. attribute:: rotation_mode
Method of updating the bone rotation, read-write.
:type: integer
Use the following constants (euler mode are named as in Blender UI but the actual axis order is reversed).
* PCHAN_ROT_QUAT(0) : use quaternioin in rotation attribute to update bone rotation
* PCHAN_ROT_XYZ(1) : use euler_rotation and apply angles on bone's Z, Y, X axis successively
* PCHAN_ROT_XZY(2) : use euler_rotation and apply angles on bone's Y, Z, X axis successively
* PCHAN_ROT_YXZ(3) : use euler_rotation and apply angles on bone's Z, X, Y axis successively
* PCHAN_ROT_YZX(4) : use euler_rotation and apply angles on bone's X, Z, Y axis successively
* PCHAN_ROT_ZXY(5) : use euler_rotation and apply angles on bone's Y, X, Z axis successively
* PCHAN_ROT_ZYX(6) : use euler_rotation and apply angles on bone's X, Y, Z axis successively
.. attribute:: channel_matrix
pose matrix in bone space (deformation of the bone due to action, constraint, etc), Read-only.
This field is updated after the graphic render, it represents the current pose.
:type: matrix [4][4]
.. attribute:: pose_matrix
pose matrix in armature space, read-only,
This field is updated after the graphic render, it represents the current pose.
:type: matrix [4][4]
.. attribute:: pose_head
position of bone head in armature space, read-only.
:type: vector [x, y, z]
.. attribute:: pose_tail
position of bone tail in armature space, read-only.
:type: vector [x, y, z]
.. attribute:: ik_min_x
minimum value of X rotation in degree (<= 0) when X rotation is limited (see ik_limit_x), read-only.
:type: float
.. attribute:: ik_max_x
maximum value of X rotation in degree (>= 0) when X rotation is limited (see ik_limit_x), read-only.
:type: float
.. attribute:: ik_min_y
minimum value of Y rotation in degree (<= 0) when Y rotation is limited (see ik_limit_y), read-only.
:type: float
.. attribute:: ik_max_y
maximum value of Y rotation in degree (>= 0) when Y rotation is limited (see ik_limit_y), read-only.
:type: float
.. attribute:: ik_min_z
minimum value of Z rotation in degree (<= 0) when Z rotation is limited (see ik_limit_z), read-only.
:type: float
.. attribute:: ik_max_z
maximum value of Z rotation in degree (>= 0) when Z rotation is limited (see ik_limit_z), read-only.
:type: float
.. attribute:: ik_stiffness_x
bone rotation stiffness in X axis, read-only.
:type: float between 0 and 1
.. attribute:: ik_stiffness_y
bone rotation stiffness in Y axis, read-only.
:type: float between 0 and 1
.. attribute:: ik_stiffness_z
bone rotation stiffness in Z axis, read-only.
:type: float between 0 and 1
.. attribute:: ik_stretch
ratio of scale change that is allowed, 0=bone can't change size, read-only.
:type: float
.. attribute:: ik_rot_weight
weight of rotation constraint when ik_rot_control is set, read-write.
:type: float between 0 and 1
.. attribute:: ik_lin_weight
weight of size constraint when ik_lin_control is set, read-write.
:type: float between 0 and 1
.. attribute:: joint_rotation
Control bone rotation in term of joint angle (for robotic applications), read-write.
When writing to this attribute, you pass a [x, y, z] vector and an appropriate set of euler angles or quaternion is calculated according to the rotation_mode.
When you read this attribute, the current pose matrix is converted into a [x, y, z] vector representing the joint angles.
The value and the meaning of the x, y, z depends on the ik_dof_x/ik_dof_y/ik_dof_z attributes:
* 1DoF joint X, Y or Z: the corresponding x, y, or z value is used an a joint angle in radiant
* 2DoF joint X+Y or Z+Y: treated as 2 successive 1DoF joints: first X or Z, then Y. The x or z value is used as a joint angle in radiant along the X or Z axis, followed by a rotation along the new Y axis of y radiants.
* 2DoF joint X+Z: treated as a 2DoF joint with rotation axis on the X/Z plane. The x and z values are used as the coordinates of the rotation vector in the X/Z plane.
* 3DoF joint X+Y+Z: treated as a revolute joint. The [x, y, z] vector represents the equivalent rotation vector to bring the joint from the rest pose to the new pose.
:type: vector [x, y, z]
.. note::
The bone must be part of an IK chain if you want to set the ik_dof_x/ik_dof_y/ik_dof_z attributes via the UI, but this will interfere with this attribute since the IK solver will overwrite the pose. You can stay in control of the armature if you create an IK constraint but do not finalize it (e.g. don't set a target) the IK solver will not run but the IK panel will show up on the UI for each bone in the chain.
.. note::
[0, 0, 0] always corresponds to the rest pose.
.. note::
You must request the armature pose to update and wait for the next graphic frame to see the effect of setting this attribute (see :data:`BL_ArmatureObject.update`).
.. note::
You can read the result of the calculation in rotation or euler_rotation attributes after setting this attribute.
.. class:: BL_ArmatureBone(PyObjectPlus)
Proxy to Blender bone structure. All fields are read-only and comply to RNA names.
All space attribute correspond to the rest pose.
.. attribute:: name
bone name.
:type: string
.. attribute:: connected
true when the bone head is struck to the parent's tail.
:type: boolean
.. attribute:: hinge
true when bone doesn't inherit rotation or scale from parent bone.
:type: boolean
.. attribute:: inherit_scale
true when bone inherits scaling from parent bone.
:type: boolean
.. attribute:: bbone_segments
number of B-bone segments.
:type: integer
.. attribute:: roll
bone rotation around head-tail axis.
:type: float
.. attribute:: head
location of head end of the bone in parent bone space.
:type: vector [x, y, z]
.. attribute:: tail
location of head end of the bone in parent bone space.
:type: vector [x, y, z]
.. attribute:: length
bone length.
:type: float
.. attribute:: arm_head
location of head end of the bone in armature space.
:type: vector [x, y, z]
.. attribute:: arm_tail
location of tail end of the bone in armature space.
:type: vector [x, y, z]
.. attribute:: arm_mat
matrix of the bone head in armature space.
:type: matrix [4][4]
.. note::
This matrix has no scale part.
.. attribute:: bone_mat
rotation matrix of the bone in parent bone space.
:type: matrix [3][3]
.. attribute:: parent
parent bone, or None for root bone.
:type: :class:`BL_ArmatureBone`
.. attribute:: children
list of bone's children.
:type: list of :class:`BL_ArmatureBone`

View File

@@ -0,0 +1,872 @@
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# Contributor(s): Campbell Barton
#
# #**** END GPL LICENSE BLOCK #****
script_help_msg = '''
Usage:
For HTML generation
-------------------
- Run this script from blenders root path once you have compiled blender
./blender.bin -b -P doc/python_api/sphinx_doc_gen.py
This will generate python files in doc/python_api/sphinx-in/,
assuming that ./blender.bin is or links to the blender executable
- Generate html docs by running...
sphinx-build doc/python_api/sphinx-in doc/python_api/sphinx-out
assuming that you have sphinx 0.6.7 installed
For PDF generation
------------------
- After you have built doc/python_api/sphinx-in (see above), run:
sphinx-build -b latex doc/python_api/sphinx-in doc/python_api/sphinx-out
cd doc/python_api/sphinx-out
make
'''
# import rpdb2; rpdb2.start_embedded_debugger('test')
import os
import inspect
import bpy
import rna_info
reload(rna_info)
# lame, python wont give some access
ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])
MethodDescriptorType = type(dict.get)
GetSetDescriptorType = type(int.real)
EXAMPLE_SET = set()
EXAMPLE_SET_USED = set()
_BPY_STRUCT_FAKE = "bpy_struct"
_BPY_FULL_REBUILD = False
def undocumented_message(module_name, type_name, identifier):
message = "Undocumented (`contribute " \
"<http://wiki.blender.org/index.php/Dev:2.5/Py/API/Documentation/Contribute" \
"?action=edit&section=new&preload=Dev:2.5/Py/API/Documentation/Contribute/Howto-message" \
"&preloadtitle=%s.%s.%s>`_)\n\n" % (module_name, type_name, identifier)
return message
def range_str(val):
'''
Converts values to strings for the range directive.
(unused function it seems)
'''
if val < -10000000: return '-inf'
if val > 10000000: return 'inf'
if type(val)==float:
return '%g' % val
else:
return str(val)
def write_example_ref(ident, fw, example_id, ext="py"):
if example_id in EXAMPLE_SET:
fw("%s.. literalinclude:: ../examples/%s.%s\n\n" % (ident, example_id, ext))
EXAMPLE_SET_USED.add(example_id)
else:
if bpy.app.debug:
print("\tskipping example:", example_id)
def write_indented_lines(ident, fn, text, strip=True):
'''
Apply same indentation to all lines in a multilines text.
'''
if text is None:
return
for l in text.split("\n"):
if strip:
fn(ident + l.strip() + "\n")
else:
fn(ident + l + "\n")
def pymethod2sphinx(ident, fw, identifier, py_func):
'''
class method to sphinx
'''
arg_str = inspect.formatargspec(*inspect.getargspec(py_func))
if arg_str.startswith("(self, "):
arg_str = "(" + arg_str[7:]
func_type = "method"
elif arg_str.startswith("(cls, "):
arg_str = "(" + arg_str[6:]
func_type = "classmethod"
else:
func_type = "staticmethod"
fw(ident + ".. %s:: %s%s\n\n" % (func_type, identifier, arg_str))
if py_func.__doc__:
write_indented_lines(ident + " ", fw, py_func.__doc__)
fw("\n")
def pyfunc2sphinx(ident, fw, identifier, py_func, is_class=True):
'''
function or class method to sphinx
'''
arg_str = inspect.formatargspec(*inspect.getargspec(py_func))
if not is_class:
func_type = "function"
# ther rest are class methods
elif arg_str.startswith("(self, "):
arg_str = "(" + arg_str[7:]
func_type = "method"
elif arg_str.startswith("(cls, "):
arg_str = "(" + arg_str[6:]
func_type = "classmethod"
else:
func_type = "staticmethod"
fw(ident + ".. %s:: %s%s\n\n" % (func_type, identifier, arg_str))
if py_func.__doc__:
write_indented_lines(ident + " ", fw, py_func.__doc__.strip())
fw("\n")
def py_descr2sphinx(ident, fw, descr, module_name, type_name, identifier):
if identifier.startswith("_"):
return
doc = descr.__doc__
if not doc:
doc = undocumented_message(module_name, type_name, identifier)
if type(descr) == GetSetDescriptorType:
fw(ident + ".. attribute:: %s\n\n" % identifier)
write_indented_lines(ident + " ", fw, doc, False)
elif type(descr) in (MethodDescriptorType, ClassMethodDescriptorType):
write_indented_lines(ident, fw, doc, False)
else:
raise TypeError("type was not GetSetDescriptorType, MethodDescriptorType or ClassMethodDescriptorType")
write_example_ref(ident, fw, module_name + "." + type_name + "." + identifier)
fw("\n")
def py_c_func2sphinx(ident, fw, module_name, type_name, identifier, py_func, is_class=True):
'''
c defined function to sphinx.
'''
# dump the docstring, assume its formatted correctly
if py_func.__doc__:
write_indented_lines(ident, fw, py_func.__doc__, False)
fw("\n")
else:
fw(ident + ".. function:: %s()\n\n" % identifier)
fw(ident + " " + undocumented_message(module_name, type_name, identifier))
def pyprop2sphinx(ident, fw, identifier, py_prop):
'''
python property to sphinx
'''
# readonly properties use "data" directive, variables use "attribute" directive
if py_prop.fset is None:
fw(ident + ".. data:: %s\n\n" % identifier)
else:
fw(ident + ".. attribute:: %s\n\n" % identifier)
write_indented_lines(ident + " ", fw, py_prop.__doc__)
if py_prop.fset is None:
fw(ident + " (readonly)\n\n")
def pymodule2sphinx(BASEPATH, module_name, module, title):
import types
attribute_set = set()
filepath = os.path.join(BASEPATH, module_name + ".rst")
file = open(filepath, "w")
fw = file.write
fw(title + "\n")
fw(("=" * len(title)) + "\n\n")
fw(".. module:: %s\n\n" % module_name)
if module.__doc__:
# Note, may contain sphinx syntax, dont mangle!
fw(module.__doc__.strip())
fw("\n\n")
write_example_ref("", fw, module_name)
# write members of the module
# only tested with PyStructs which are not exactly modules
for key, descr in sorted(type(module).__dict__.items()):
if type(descr) == types.MemberDescriptorType:
if descr.__doc__:
fw(".. data:: %s\n\n" % key)
write_indented_lines(" ", fw, descr.__doc__, False)
attribute_set.add(key)
fw("\n")
del key, descr
classes = []
for attribute in sorted(dir(module)):
if not attribute.startswith("_"):
if attribute in attribute_set:
continue
if attribute.startswith("n_"): # annoying exception, needed for bpy.app
continue
value = getattr(module, attribute)
value_type = type(value)
if value_type == types.FunctionType:
pyfunc2sphinx("", fw, attribute, value, is_class=False)
elif value_type in (types.BuiltinMethodType, types.BuiltinFunctionType): # both the same at the moment but to be future proof
# note: can't get args from these, so dump the string as is
# this means any module used like this must have fully formatted docstrings.
py_c_func2sphinx("", fw, module_name, module, attribute, value, is_class=False)
elif value_type == type:
classes.append((attribute, value))
elif value_type in (bool, int, float, str, tuple):
# constant, not much fun we can do here except to list it.
# TODO, figure out some way to document these!
fw(".. data:: %s\n\n" % attribute)
write_indented_lines(" ", fw, "constant value %s" % repr(value), False)
fw("\n")
else:
print("\tnot documenting %s.%s" % (module_name, attribute))
continue
attribute_set.add(attribute)
# TODO, more types...
# write collected classes now
for (type_name, value) in classes:
# May need to be its own function
fw(".. class:: %s\n\n" % type_name)
if value.__doc__:
write_indented_lines(" ", fw, value.__doc__, False)
fw("\n")
write_example_ref(" ", fw, module_name + "." + type_name)
descr_items = [(key, descr) for key, descr in sorted(value.__dict__.items()) if not key.startswith("__")]
for key, descr in descr_items:
if type(descr) == ClassMethodDescriptorType:
py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
for key, descr in descr_items:
if type(descr) == MethodDescriptorType:
py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
for key, descr in descr_items:
if type(descr) == GetSetDescriptorType:
py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
fw("\n\n")
file.close()
def rna2sphinx(BASEPATH):
structs, funcs, ops, props = rna_info.BuildRNAInfo()
try:
os.mkdir(BASEPATH)
except:
pass
# conf.py - empty for now
filepath = os.path.join(BASEPATH, "conf.py")
file = open(filepath, "w")
fw = file.write
version_string = bpy.app.version_string.split("(")[0]
if bpy.app.build_revision != "Unknown":
version_string = version_string + " r" + bpy.app.build_revision
# for use with files
version_string_fp = "_".join(str(v) for v in bpy.app.version)
fw("project = 'Blender'\n")
# fw("master_doc = 'index'\n")
fw("copyright = u'Blender Foundation'\n")
fw("version = '%s - UNSTABLE API'\n" % version_string)
fw("release = '%s - UNSTABLE API'\n" % version_string)
fw("html_theme = 'blender-org'\n")
fw("html_theme_path = ['../']\n")
fw("html_favicon = 'favicon.ico'\n")
# not helpful since the source us generated, adds to upload size.
fw("html_copy_source = False\n")
fw("\n")
# needed for latex, pdf gen
fw("latex_documents = [ ('contents', 'contents.tex', 'Blender Index', 'Blender Foundation', 'manual'), ]\n")
fw("latex_paper_size = 'a4paper'\n")
file.close()
filepath = os.path.join(BASEPATH, "contents.rst")
file = open(filepath, "w")
fw = file.write
fw("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n")
fw(" Blender Documentation contents\n")
fw("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n")
fw("\n")
fw("This document is an API reference for Blender %s. built %s.\n" % (version_string, bpy.app.build_date))
fw("\n")
fw("An introduction to Blender and Python can be found at <http://wiki.blender.org/index.php/Dev:2.5/Py/API/Intro>\n")
fw("\n")
fw("`A PDF version of this document is also available <blender_python_reference_%s.pdf>`__\n" % version_string_fp)
fw("\n")
fw(".. warning:: The Python API in Blender is **UNSTABLE**, It should only be used for testing, any script written now may break in future releases.\n")
fw(" \n")
fw(" The following areas are subject to change.\n")
fw(" * operator names and arguments\n")
fw(" * render api\n")
fw(" * function calls with the data api (any function calls with values accessed from bpy.data), including functions for importing and exporting meshes\n")
fw(" * class registration (Operator, Panels, Menus, Headers)\n")
fw(" * modules: bpy.props, blf)\n")
fw(" * members in the bpy.context have to be reviewed\n")
fw(" * python defined modal operators, especially drawing callbacks are highly experemental\n")
fw(" \n")
fw(" These parts of the API are relatively stable and are unlikely to change significantly\n")
fw(" * data API, access to attributes of blender data such as mesh verts, material color, timeline frames and scene objects\n")
fw(" * user interface functions for defining buttons, creation of menus, headers, panels\n")
fw(" * modules: bgl, mathutils and geometry\n")
fw(" * game engine modules\n")
fw("\n")
fw("===================\n")
fw("Application Modules\n")
fw("===================\n")
fw("\n")
fw(".. toctree::\n")
fw(" :maxdepth: 1\n\n")
fw(" bpy.data.rst\n\n") # note: not actually a module
fw(" bpy.ops.rst\n\n")
fw(" bpy.types.rst\n\n")
# py modules
fw(" bpy.utils.rst\n\n")
fw(" bpy.path.rst\n\n")
fw(" bpy.app.rst\n\n")
# C modules
fw(" bpy.props.rst\n\n")
fw("==================\n")
fw("Standalone Modules\n")
fw("==================\n")
fw("\n")
fw(".. toctree::\n")
fw(" :maxdepth: 1\n\n")
fw(" mathutils.rst\n\n")
fw(" blf.rst\n\n")
fw(" aud.rst\n\n")
# game engine
fw("===================\n")
fw("Game Engine Modules\n")
fw("===================\n")
fw("\n")
fw(".. toctree::\n")
fw(" :maxdepth: 1\n\n")
fw(" bge.types.rst\n\n")
fw(" bge.logic.rst\n\n")
fw(" bge.render.rst\n\n")
fw(" bge.events.rst\n\n")
file.close()
# internal modules
filepath = os.path.join(BASEPATH, "bpy.ops.rst")
file = open(filepath, "w")
fw = file.write
fw("Operators (bpy.ops)\n")
fw("===================\n\n")
fw(".. toctree::\n")
fw(" :glob:\n\n")
fw(" bpy.ops.*\n\n")
file.close()
filepath = os.path.join(BASEPATH, "bpy.types.rst")
file = open(filepath, "w")
fw = file.write
fw("Types (bpy.types)\n")
fw("=================\n\n")
fw(".. toctree::\n")
fw(" :glob:\n\n")
fw(" bpy.types.*\n\n")
file.close()
# not actually a module, only write this file so we
# can reference in the TOC
filepath = os.path.join(BASEPATH, "bpy.data.rst")
file = open(filepath, "w")
fw = file.write
fw("Data Access (bpy.data)\n")
fw("======================\n\n")
fw(".. module:: bpy\n")
fw("\n")
fw("This module is used for all blender/python access.\n")
fw("\n")
fw(".. literalinclude:: ../examples/bpy.data.py\n")
fw("\n")
fw(".. data:: data\n")
fw("\n")
fw(" Access to blenders internal data\n")
fw("\n")
fw(" :type: :class:`bpy.types.BlendData`\n")
file.close()
EXAMPLE_SET_USED.add("bpy.data")
# python modules
from bpy import utils as module
pymodule2sphinx(BASEPATH, "bpy.utils", module, "Utilities (bpy.utils)")
from bpy import path as module
pymodule2sphinx(BASEPATH, "bpy.path", module, "Path Utilities (bpy.path)")
# C modules
from bpy import app as module
pymodule2sphinx(BASEPATH, "bpy.app", module, "Application Data (bpy.app)")
from bpy import props as module
pymodule2sphinx(BASEPATH, "bpy.props", module, "Property Definitions (bpy.props)")
import mathutils as module
pymodule2sphinx(BASEPATH, "mathutils", module, "Math Types & Utilities (mathutils)")
del module
import blf as module
pymodule2sphinx(BASEPATH, "blf", module, "Font Drawing (blf)")
del module
import aud as module
pymodule2sphinx(BASEPATH, "aud", module, "Audio System (aud)")
del module
## game engine
import shutil
# copy2 keeps time/date stamps
shutil.copy2(os.path.join(BASEPATH,"..","rst","bge.types.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH,"..","rst","bge.logic.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH,"..","rst","bge.render.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH,"..","rst","bge.events.rst"), BASEPATH)
if 0:
filepath = os.path.join(BASEPATH, "bpy.rst")
file = open(filepath, "w")
fw = file.write
fw("\n")
title = ":mod:`bpy` --- Blender Python Module"
fw("%s\n%s\n\n" % (title, "=" * len(title)))
fw(".. module:: bpy.types\n\n")
file.close()
def write_param(ident, fw, prop, is_return=False):
if is_return:
id_name = "return"
id_type = "rtype"
kwargs = {"as_ret": True, "class_fmt": ":class:`%s`"}
identifier = ""
else:
id_name = "arg"
id_type = "type"
kwargs = {"as_arg": True, "class_fmt": ":class:`%s`"}
identifier = " %s" % prop.identifier
type_descr = prop.get_type_description(**kwargs)
if prop.name or prop.description:
fw(ident + ":%s%s: %s\n" % (id_name, identifier, ", ".join(val for val in (prop.name, prop.description) if val)))
fw(ident + ":%s%s: %s\n" % (id_type, identifier, type_descr))
def write_struct(struct):
#if not struct.identifier.startswith("Sc") and not struct.identifier.startswith("I"):
# return
#if not struct.identifier == "Object":
# return
filepath = os.path.join(BASEPATH, "bpy.types.%s.rst" % struct.identifier)
file = open(filepath, "w")
fw = file.write
base_id = getattr(struct.base, "identifier", "")
if _BPY_STRUCT_FAKE:
if not base_id:
base_id = _BPY_STRUCT_FAKE
if base_id:
title = "%s(%s)" % (struct.identifier, base_id)
else:
title = struct.identifier
fw("%s\n%s\n\n" % (title, "=" * len(title)))
fw(".. module:: bpy.types\n\n")
base_ids = [base.identifier for base in struct.get_bases()]
if _BPY_STRUCT_FAKE:
base_ids.append(_BPY_STRUCT_FAKE)
base_ids.reverse()
if base_ids:
if len(base_ids) > 1:
fw("base classes --- ")
else:
fw("base class --- ")
fw(", ".join((":class:`%s`" % base_id) for base_id in base_ids))
fw("\n\n")
subclass_ids = [s.identifier for s in structs.values() if s.base is struct if not rna_info.rna_id_ignore(s.identifier)]
if subclass_ids:
fw("subclasses --- \n" + ", ".join((":class:`%s`" % s) for s in subclass_ids) + "\n\n")
base_id = getattr(struct.base, "identifier", "")
if _BPY_STRUCT_FAKE:
if not base_id:
base_id = _BPY_STRUCT_FAKE
if base_id:
fw(".. class:: %s(%s)\n\n" % (struct.identifier, base_id))
else:
fw(".. class:: %s\n\n" % struct.identifier)
fw(" %s\n\n" % struct.description)
# properties sorted in alphabetical order
sorted_struct_properties = struct.properties[:]
sorted_struct_properties.sort(key=lambda prop: prop.identifier)
for prop in sorted_struct_properties:
type_descr = prop.get_type_description(class_fmt=":class:`%s`")
# readonly properties use "data" directive, variables properties use "attribute" directive
if 'readonly' in type_descr:
fw(" .. data:: %s\n\n" % prop.identifier)
else:
fw(" .. attribute:: %s\n\n" % prop.identifier)
if prop.description:
fw(" %s\n\n" % prop.description)
fw(" :type: %s\n\n" % type_descr)
# python attributes
py_properties = struct.get_py_properties()
py_prop = None
for identifier, py_prop in py_properties:
pyprop2sphinx(" ", fw, identifier, py_prop)
del py_properties, py_prop
for func in struct.functions:
args_str = ", ".join(prop.get_arg_default(force=False) for prop in func.args)
fw(" .. %s:: %s(%s)\n\n" % ("classmethod" if func.is_classmethod else "method", func.identifier, args_str))
fw(" %s\n\n" % func.description)
for prop in func.args:
write_param(" ", fw, prop)
if len(func.return_values) == 1:
write_param(" ", fw, func.return_values[0], is_return=True)
elif func.return_values: # multiple return values
fw(" :return (%s):\n" % ", ".join(prop.identifier for prop in func.return_values))
for prop in func.return_values:
type_descr = prop.get_type_description(as_ret=True, class_fmt=":class:`%s`")
descr = prop.description
if not descr:
descr = prop.name
fw(" `%s`, %s, %s\n\n" % (prop.identifier, descr, type_descr))
fw("\n")
# python methods
py_funcs = struct.get_py_functions()
py_func = None
for identifier, py_func in py_funcs:
pyfunc2sphinx(" ", fw, identifier, py_func, is_class=True)
del py_funcs, py_func
lines = []
if struct.base or _BPY_STRUCT_FAKE:
bases = list(reversed(struct.get_bases()))
# props
lines[:] = []
if _BPY_STRUCT_FAKE:
descr_items = [(key, descr) for key, descr in sorted(bpy.types.Struct.__bases__[0].__dict__.items()) if not key.startswith("__")]
if _BPY_STRUCT_FAKE:
for key, descr in descr_items:
if type(descr) == GetSetDescriptorType:
lines.append(" * :class:`%s.%s`\n" % (_BPY_STRUCT_FAKE, key))
for base in bases:
for prop in base.properties:
lines.append(" * :class:`%s.%s`\n" % (base.identifier, prop.identifier))
for identifier, py_prop in base.get_py_properties():
lines.append(" * :class:`%s.%s`\n" % (base.identifier, identifier))
for identifier, py_prop in base.get_py_properties():
lines.append(" * :class:`%s.%s`\n" % (base.identifier, identifier))
if lines:
fw(".. rubric:: Inherited Properties\n\n")
fw(".. hlist::\n")
fw(" :columns: 2\n\n")
for line in lines:
fw(line)
fw("\n")
# funcs
lines[:] = []
if _BPY_STRUCT_FAKE:
for key, descr in descr_items:
if type(descr) == MethodDescriptorType:
lines.append(" * :class:`%s.%s`\n" % (_BPY_STRUCT_FAKE, key))
for base in bases:
for func in base.functions:
lines.append(" * :class:`%s.%s`\n" % (base.identifier, func.identifier))
for identifier, py_func in base.get_py_functions():
lines.append(" * :class:`%s.%s`\n" % (base.identifier, identifier))
if lines:
fw(".. rubric:: Inherited Functions\n\n")
fw(".. hlist::\n")
fw(" :columns: 2\n\n")
for line in lines:
fw(line)
fw("\n")
lines[:] = []
if struct.references:
# use this otherwise it gets in the index for a normal heading.
fw(".. rubric:: References\n\n")
fw(".. hlist::\n")
fw(" :columns: 2\n\n")
for ref in struct.references:
ref_split = ref.split(".")
if len(ref_split) > 2:
ref = ref_split[-2] + "." + ref_split[-1]
fw(" * :class:`%s`\n" % ref)
fw("\n")
for struct in structs.values():
# TODO, rna_info should filter these out!
if "_OT_" in struct.identifier:
continue
write_struct(struct)
# special case, bpy_struct
if _BPY_STRUCT_FAKE:
filepath = os.path.join(BASEPATH, "bpy.types.%s.rst" % _BPY_STRUCT_FAKE)
file = open(filepath, "w")
fw = file.write
fw("%s\n" % _BPY_STRUCT_FAKE)
fw("=" * len(_BPY_STRUCT_FAKE) + "\n")
fw("\n")
fw(".. module:: bpy.types\n")
fw("\n")
subclass_ids = [s.identifier for s in structs.values() if s.base is None if not rna_info.rna_id_ignore(s.identifier)]
if subclass_ids:
fw("subclasses --- \n" + ", ".join((":class:`%s`" % s) for s in sorted(subclass_ids)) + "\n\n")
fw(".. class:: %s\n\n" % _BPY_STRUCT_FAKE)
fw(" built-in base class for all classes in bpy.types.\n\n")
fw(" .. note::\n\n")
fw(" Note that bpy.types.%s is not actually available from within blender, it only exists for the purpose of documentation.\n\n" % _BPY_STRUCT_FAKE)
descr_items = [(key, descr) for key, descr in sorted(bpy.types.Struct.__bases__[0].__dict__.items()) if not key.startswith("__")]
for key, descr in descr_items:
if type(descr) == MethodDescriptorType: # GetSetDescriptorType, GetSetDescriptorType's are not documented yet
py_descr2sphinx(" ", fw, descr, "bpy.types", _BPY_STRUCT_FAKE, key)
for key, descr in descr_items:
if type(descr) == GetSetDescriptorType:
py_descr2sphinx(" ", fw, descr, "bpy.types", _BPY_STRUCT_FAKE, key)
# operators
def write_ops():
API_BASEURL='https://svn.blender.org/svnroot/bf-blender/trunk/blender/release/scripts'
fw = None
last_mod = ''
for op_key in sorted(ops.keys()):
op = ops[op_key]
if last_mod != op.module_name:
filepath = os.path.join(BASEPATH, "bpy.ops.%s.rst" % op.module_name)
file = open(filepath, "w")
fw = file.write
title = "%s Operators" % (op.module_name[0].upper() + op.module_name[1:])
fw("%s\n%s\n\n" % (title, "=" * len(title)))
fw(".. module:: bpy.ops.%s\n\n" % op.module_name)
last_mod = op.module_name
args_str = ", ".join(prop.get_arg_default(force=True) for prop in op.args)
fw(".. function:: %s(%s)\n\n" % (op.func_name, args_str))
# if the description isn't valid, we output the standard warning
# with a link to the wiki so that people can help
if not op.description or op.description == "(undocumented operator)":
operator_description = undocumented_message('bpy.ops',op.module_name,op.func_name)
else:
operator_description = op.description
fw(" %s\n\n" % operator_description)
for prop in op.args:
write_param(" ", fw, prop)
if op.args:
fw("\n")
location = op.get_location()
if location != (None, None):
fw(" :file: `%s <%s/%s>`_:%d\n\n" % (location[0],API_BASEURL,location[0],location[1]))
write_ops()
file.close()
def main():
import bpy
if 'bpy' not in dir():
print("\nError, this script must run from inside blender2.5")
print(script_help_msg)
else:
import shutil
script_dir = os.path.dirname(__file__)
path_in = os.path.join(script_dir,'sphinx-in')
path_out = os.path.join(script_dir,'sphinx-out')
path_examples = os.path.join(script_dir,'examples')
# only for partial updates
path_in_tmp = path_in + "-tmp"
if not os.path.exists(path_in):
os.mkdir(path_in)
for f in os.listdir(path_examples):
if f.endswith(".py"):
EXAMPLE_SET.add(os.path.splitext(f)[0])
# only for full updates
if _BPY_FULL_REBUILD:
shutil.rmtree(path_in, True)
shutil.rmtree(path_out, True)
else:
# write here, then move
shutil.rmtree(path_in_tmp, True)
rna2sphinx(path_in_tmp)
if not _BPY_FULL_REBUILD:
import filecmp
# now move changed files from 'path_in_tmp' --> 'path_in'
file_list_path_in = set(os.listdir(path_in))
file_list_path_in_tmp = set(os.listdir(path_in_tmp))
# remove deprecated files that have been removed.
for f in sorted(file_list_path_in):
if f not in file_list_path_in_tmp:
print("\tdeprecated: %s" % f)
os.remove(os.path.join(path_in, f))
# freshen with new files.
for f in sorted(file_list_path_in_tmp):
f_from = os.path.join(path_in_tmp, f)
f_to = os.path.join(path_in, f)
do_copy = True
if f in file_list_path_in:
if filecmp.cmp(f_from, f_to):
do_copy = False
if do_copy:
print("\tupdating: %s" % f)
shutil.copy(f_from, f_to)
'''else:
print("\tkeeping: %s" % f) # eh, not that useful'''
EXAMPLE_SET_UNUSED = EXAMPLE_SET - EXAMPLE_SET_USED
if EXAMPLE_SET_UNUSED:
print("\nUnused examples found in '%s'..." % path_examples)
for f in EXAMPLE_SET_UNUSED:
print(" %s.py" % f)
print(" %d total\n" % len(EXAMPLE_SET_UNUSED))
import sys
sys.exit()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,37 @@
#!/bin/sh
# run from the blender source dir
# bash source/blender/python/doc/sphinx_doc_gen.sh
# ssh upload means you need an account on the server
BLENDER="./blender.bin"
SSH_HOST="ideasman42@emo.blender.org"
SSH_UPLOAD="/data/www/vhosts/www.blender.org/documentation" # blender_python_api_VERSION, added after
# sed string from hell, 'Blender 2.53 (sub 1) Build' --> '2_53_1'
# "_".join(str(v) for v in bpy.app.version)
# custom blender vars
blender_srcdir=$(dirname $0)/../../
blender_version=$(grep BLENDER_VERSION $blender_srcdir/source/blender/blenkernel/BKE_blender.h | tr -dc 0-9)
blender_subversion=$(grep BLENDER_SUBVERSION $blender_srcdir/source/blender/blenkernel/BKE_blender.h | tr -dc 0-9)
BLENDER_VERSION=$(expr $blender_version / 100)_$(expr $blender_version % 100)_$blender_subversion
BLENDER_VERSION=`$BLENDER --version | cut -f2-4 -d" " | sed 's/(//g' | sed 's/)//g' | sed 's/ sub /./g' | sed 's/\./_/g'`
SSH_UPLOAD_FULL=$SSH_UPLOAD/"blender_python_api_"$BLENDER_VERSION
SPHINXBASE=doc/python_api/
# dont delete existing docs, now partial updates are used for quick builds.
$BLENDER --background --python $SPHINXBASE/sphinx_doc_gen.py
# html
sphinx-build $SPHINXBASE/sphinx-in $SPHINXBASE/sphinx-out
cp $SPHINXBASE/sphinx-out/contents.html $SPHINXBASE/sphinx-out/index.html
ssh ideasman42@emo.blender.org 'rm -rf '$SSH_UPLOAD_FULL'/*'
rsync --progress -avze "ssh -p 22" $SPHINXBASE/sphinx-out/* $SSH_HOST:$SSH_UPLOAD_FULL/
# pdf
sphinx-build -b latex $SPHINXBASE/sphinx-in $SPHINXBASE/sphinx-out
cd $SPHINXBASE/sphinx-out
make
cd -
rsync --progress -avze "ssh -p 22" $SPHINXBASE/sphinx-out/contents.pdf $SSH_HOST:$SSH_UPLOAD_FULL/blender_python_reference_$BLENDER_VERSION.pdf