Operand Binary Options
Calculadora binária (Deseja calcular com operandos decimais Você deve convertê-los primeiro.) Sobre a Calculadora Binária Esta é uma calculadora binária de precisão arbitrária. Pode adicionar. subtrair. multiplicar. Ou dividir dois números binários. Ele pode operar em inteiros muito grandes e valores fracionários muito pequenos 8212 e combinações de ambos. Esta calculadora é, por design, muito simples. Você pode usá-lo para explorar números binários em sua forma mais básica. Ele opera em ldquopurerdquo números binários, não formatos de número de computador como complemento two8217s ou ponto flutuante iEEE binário. Como usar a calculadora binária Digite um operando em cada caixa. Cada operando deve ser um número positivo ou negativo sem vírgulas ou espaços, não expresso como uma fração, e não em notação científica. Os valores fracionários são indicados com um ponto de raiz (lsquo. rsquo, não lsquo, rsquo), e os números negativos são prefixados com um sinal de menos (ldquo-rdquo). Selecione uma operação (, 8211, /). Altere o número de bits que deseja exibir no resultado binário, se diferente do padrão (isso se aplica somente à divisão e, em seguida, somente quando a resposta tiver uma parte fracionária infinita). Clique em lsquoCalculatersquo para executar a operação. Clique em lsquoClearrsquo para redefinir o formulário e começar do zero. Se você quiser mudar um operando, basta digitar sobre o número original e clicar em lsquoCalculatersquo 8212 não é necessário clicar primeiro em lsquoClearrsquo. Da mesma forma, você pode alterar o operador e manter os operandos como está. Além do resultado da operação, o número de dígitos nos operandos eo resultado é exibido. Por exemplo, ao calcular 1.1101 111.100011 1101.1010110111, a caixa ldquoNum Digitsrdquo exibe ldquo1.4 3.6 4.10rdquo. Isto significa que o operando 1 tem um dígito em sua parte inteira e quatro dígitos em sua parte fracionária, o operando 2 tem três dígitos em sua parte inteira e seis dígitos em sua parte fracionária eo resultado tem quatro dígitos em sua parte inteira e dez dígitos Em sua parte fracionária. A adição, subtração e multiplicação produzem sempre um resultado finito, mas a divisão pode (na verdade, na maioria dos casos) produzir um valor fracionário infinito (repetitivo). Os resultados infinitos são truncados 8212 não arredondados 8212 para o número especificado de bits. Os resultados infinitos são anotados com uma elipse (8230) anexada ao resultado, e com um símbolo lsquo8734rsquo como o número de dígitos fracionários. Para divisões que representam frações diádicas. O resultado será finito. E exibido com precisão total 8212 independentemente da configuração para o número de bits fracionários. Por exemplo, 1/1010 a 24 bits fracionários é 0.0001100110011001100110018230, com ldquoNum Digitsrdquo ldquo1.0 / 4.0 0.8734rdquo 11/100 0.11, com ldquoNum Digitsrdquo ldquo2.0 / 3.0 0.2rdquo. Usando a calculadora para explorar aritmética de ponto flutuante Embora essa calculadora implemente aritmética binária pura, você pode usá-la para explorar a aritmética de ponto flutuante. Por exemplo, digamos que você queria saber por que, usando IEEE dupla precisão binário ponto flutuante aritmética, 129,95 10 1299,5, mas 129,95 100 12994.999999999998181010596454143524169921875. Há duas fontes de imprecisão nesse cálculo: conversão decimal em ponto flutuante. E aritmética binária de precisão limitada. Decimal a conversão de ponto flutuante introduz inexato porque um operando decimal pode não ter um ponto flutuante exato equivalente aritmética binária de precisão limitada introduz inexato porque um cálculo binário pode produzir mais bits do que pode ser armazenado. Nestes casos, ocorre o arredondamento. 10 e 100 (ambos os decimais) têm equivalentes de ponto flutuante exato (1010 e 1100100, respectivamente), mas 129,95 tem apenas uma representação aproximada. Meu conversor decimal para binário irá dizer-lhe que, em puro binário, 129.95 tem uma infinita repetição fração: 10000001.111100110011001100110011001100110011001100110 011 8230 Arredondado para os 53 bits de dupla precisão, it8217s que é 129.94999999999998863131622783839702606201171875 em decimal. 129,95 10 129,95 10 é calculado como que é igual a 10100010011.011111111111111111111111111111111111111111 1 Isso é 54 bits significativos de comprimento, então quando it8217s arredondado para 53 bits torna-se 129,95 100 129,95 100 é calculado como o que é igual a 110010110011111111111111 011 Este é 56 bits significativos de comprimento, então quando 8217s arredondado para 53 bits torna-se o que é igual a 12994.999999999998181010596454143524169921875 Discussão Para trabalhar com este exemplo, você tinha que agir como um computador, tão tedioso como era. Primeiro, você tinha que converter os operandos para binário, arredondando-os se necessário, então, você tinha que multiplicá-los, e arredondar o resultado. Por razões práticas, o tamanho das entradas 8212 e o número de bits fracionários num resultado de divisão infinita 8212 é limitado. Se exceder estes limites, receberá uma mensagem de erro. Mas dentro destes limites, todos os resultados serão precisos (no caso da divisão, os resultados são precisos através da posição de bit truncada). Copy Copy 2005 a 2012 Eugene K. Ressler. Este manual é para o esboço. Versão 0.3 (build 7), sexta-feira, fevereiro 24, 2012, um programa que converte descrições de cenas tridimensionais simples em desenhos de linha. Esta versão gera PSTricks ou código PGF / TikZ adequado para uso com o sistema de processamento de documentos TeX. O esboço é software livre. Você pode redistribuí-lo e / ou modificá-lo sob os termos da GNU General Public License, tal como publicado pela Free Software Foundation ou versão 3, ou (a sua opção) qualquer versão posterior. O Sketch é distribuído com a esperança de que seja útil, mas SEM QUALQUER GARANTIA, mesmo sem a garantia implícita de COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM DETERMINADO PROPÓSITO. Consulte a Licença Pública Geral GNU para obter mais detalhes. Você deve ter recebido uma cópia da Licença Pública Geral GNU juntamente com sketch ver o arquivo COPYING. txt. Caso contrário, consulte gnu. org/copyleft. Sobre o esboço. Por que o esboço existe eo que ele faz. Introdução pelo exemplo. A maioria dos recursos mostrados como código de trabalho. Idioma de entrada. Sintaxe e semântica dos comandos de esboço. Construindo um desenho. Como usar o sketch de forma produtiva. Linha de comando. Opções e seu uso. Instalando o sketch. Construção e instalação a partir de fontes. Índice de sintaxe Índice --- A lista detalhada do nó --- Introdução pelo exemplo Olá mundo. Programa de esboço mais simples possível. Opções de desenho. Controlando a aparência do objeto. Desenho de um sólido. Desenho de um objeto com aparência 3d. Objetos especiais. Colocar TeX sobre, em, ou sob desenhos. Objeto transforma. Girar, traduzir, dimensionar e outros. Objetos repetidos. Fazendo cópias transformadas. Objetos varridos. Varrer objetos no espaço para criar novas formas. Pontos. Desenhe pontos. Linhas. Desenhar polilinhas. Curvas. Desenhe curvas. Polígonos. Desenhe polígonos. Especiais. Incorporar LaTeX e PSTricks brutos. Varreduras Desenhe varredura de pontos e polilinhas. Blocos. Agrupar outros estiráveis. Repita. Desenhe cópias transformadas de objetos. Coloca. Desenhe um objeto transformado. Pontos varridos. Pontos varridos fazem linhas ou polígonos. Linhas varridas. As linhas varridas fazem superfícies abertas ou fechadas. Polígonos varridos. Polígonos varridos fazem superfícies fechadas. Blocos varridos. Bloco varrido bloco de varreduras. Varrer a divisão da face. Fixação de faces entortadas com triângulos. Opções globais. Atributos de todo o desenho. Câmera. Uma transformação final da câmera da cena. Caixa de imagem. Definir a caixa delimitadora e recorte 2d. Quadro. Adicionando uma caixa ao redor do desenho. Língua. Definir o idioma de saída. Construindo um desenho Remoção de superfície oculta e divisão de polígonos Estatísticas. Números de desempenho na classificação de profundidade. Erros e anomalias. Imperfeições nesta implementação. 1 Sobre o sketch O Sketch é um sistema pequeno e simples para a produção de desenhos em linha de objetos e cenas bidimensionais ou tridimensionais. Começou como uma maneira de fazer ilustrações para um livro de texto depois que não pudemos encontrar nenhuma ferramenta adequada para esta finalidade. Processadores de cena existentes enfatizaram GUIs e / ou foto-realismo, ambos un-useful para nós. Nós queríamos produzir ilustrações finamente trabalhadas, matematicamente-baseadas com nenhum detalhe estranho. Sketch aceita uma linguagem de descrição de cena minúscula e gera PSTricks ou código TikZ / PGF para LaTeX. A linguagem de esboço é semelhante a PSTricks. Tornando mais fácil para aprender para os usuários atuais PSTricks. Consulte pstricks. de para obter informações sobre PSTricks. TikZ / PGF é semelhante. Veja sourceforge. net/projects/pgf. Pode-se facilmente incluir desenhos PSTricks ou TikZ / PGF arbitrários e texto sobre, dentro ou sob desenhos de esboço, proporcionando acesso ao poder total do texto LaTeX e formatação de matemática em uma configuração tridimensional. 1.1 Relatar bugs e recomendar melhorias. O grupo groups. google/group/sketch-users é o melhor local para relatar bugs e fazer melhorias. Um segundo método que provavelmente produzirá uma resposta mais lenta é o e-mail para sketchfrontiernet. net. Vamos tentar responder, mas não posso prometer. Em todo o caso, não seja ofendido se uma resposta não é forthcoming. Foram apenas agitado e irá obter a sua sugestão eventualmente. Para erros, anexe um arquivo de entrada de esboço que causa o mau comportamento. Incorporar comentários que explicam o que procurar no comportamento do sketch ou da sua saída. Uma recomendação de melhoria de uma pessoa desconhecida conta como um voto. Usamos o total de votos para decidir o que fazer em seguida, conforme os recursos o permitam. Reservamo-nos o direito de atribuir qualquer número de votos a sugestões de pessoas que foram úteis e solidárias no passado. 1.2 Contribuições Se você pretende implementar um aprimoramento do seu próprio, isso é ótimo Considere colaborar conosco primeiro para ver se já estavam trabalhando em sua idéia ou se podemos usar o seu trabalho no lançamento oficial. 2 Introdução por exemplo O idioma de entrada do esboço parecerá familiar aos usuários do pacote PSTricks para LaTeX. O programa a seguir desenha um polígono triangular perfurado por uma linha. O sistema de coordenadas é um padrão cartesiano direito. Olá Mundo. Programa de esboço mais simples possível. Opções de desenho. Controlando a aparência do objeto. Desenho de um sólido. Desenho de um objeto com aparência 3d. Objetos especiais. Colocar TeX sobre, em, ou sob desenhos. Objeto transforma. Girar, traduzir, dimensionar e outros. Objetos repetidos. Fazendo cópias transformadas. Objetos varridos. Varrer objetos no espaço para criar novas formas. 2.1 Hello world O programa de esboço acima é quase o mais simples possível, o equivalente a um programa ldquohello worldrdquo que você pode encontrar no início de um texto de linguagem de programação. Se ele é salvo no arquivo simple. sk. Então o comando cria um arquivo simple. tex contendo comandos PSTricks para desenhar esses objetos no papel. O conteúdo de simple. tex tem este aspecto. O algoritmo de superfície oculta do esboço dividiu a linha em duas partes e ordenou os três objetos resultantes para que a porção correta da linha ficasse oculta. Se você notou que a projeção que estamos usando parece equivalente a apagar a coordenada z dos pontos de entrada tridimensionais, acaricie-se nas costas. Você está certo. Isso é chamado de projeção paralela. O eixo de coordenadas z está apontando para fora do papel para nós, enquanto os eixos x e y apontam para a direita e para cima como de costume. O arquivo de imagem resultante pode ser incluído em um documento LaTeX com entrada. Como alternativa, adicionar a opção de linha de comando - T 1 faz com que o pspicture seja embrulhado em um documento curto, mas completo, pronto para executar o LaTeX. Em um documento concluído, composto, a imagem se parece com isso. (Os eixos foram adicionados em cinza claro.) É importante saber que apenas o ldquooutsiderdquo de um polígono é normalmente desenhado. O exterior é onde os vértices dados no comando do polígono aparecem no sentido anti-horário. Assim, se o comando acima tivesse sido o polígono não apareceria na imagem. Teria sido eliminado da cena. Este comportamento de abate pode parecer estranho, mas fique atento. 2.2 Opções Muitos PSTricks e TikZ / PGF opções funcionam muito bem no esboço. Se gerar PSTricks. O código produz Para produzir TikZ / PGF. O código correspondente é O global final instrui o esboço para produzir o código TikZ / PGF como saída em vez do padrão, PSTricks. Observe que as opções de cores de preenchimento de polígono e estilo de linha estão em conformidade com as regras de sintaxe TikZ. A saída TikZ / PGF resultante é. Os restantes exemplos deste manual estão no estilo PSTricks. 2.3 Desenho de um sólido Vamos tentar algo mais emocionante. O esboço não tem nenhuma noção de um sólido, mas as faces poligonais podem ser usadas para representar o limite de um sólido. Ao exemplo anterior, vamos adicionar mais três polígonos triangulares para fazer as faces de um tetraedro irregular. Este exemplo usa definições. Que começam com def. Estes definem ou atribuem nomes a pontos, que estão então disponíveis como referências, juntando os nomes entre parênteses, p. (Foo). Os parênteses indicam que os nomes referem-se a pontos que são necessários. Não pode haver nenhum espaço em branco entre eles eo nome. Como você pode ver, os comentários começam com como em TeX e estendem ao fim da linha (embora funcionará também). O espaço em branco, incluindo espaços, guias e linhas em branco, não tem efeito na linguagem de desenho. Se olharmos para dentro do arquivo TeX produzido pelo sketch. Haverá apenas três polígonos. O quarto foi abatido porque é um ldquoback facerdquo do tetraedro, invisível à nossa vista. É desnecessário, e por isso é removido. Em alguns desenhos, os polígonos atuam como superfícies sólidas de espessura zero, com ambos os lados visíveis ao invés de como faces de objetos sólidos, onde as faces traseiras podem ser descartadas. Para sólidos de espessura zero, o abate é um problema. Uma solução é usar um par de polígonos de esboço para cada face de espessura zero, idênticos exceto com ordens de vértice opostas. Isso é difícil de manejar e caro. Uma maneira melhor é definir a opção interna do sketch cull para false da maneira usual PSTricks. O seguinte mostra a mesma forma de hélice desenhada primeiro com culltrue (o padrão) e depois cullfalse. Bem em breve ver como produzir essas hélices com algumas linhas de código de linguagem de esboço. Pode ser tentador transformar o abate gratuitamente para que a ordem dos vértices possa ser ignorada. Isso não é uma boa idéia porque o tamanho do arquivo de saída eo tempo de processamento TeX e Postscript dependem do número de polígonos de saída. O abate geralmente melhora o desempenho por um fator de dois. Por outro lado, definir cullfalse globalmente é razoável durante a depuração. Consulte Opções globais e Limites de detecção de erros. 2.4 Objetos especiais Podemos adicionar rótulos a um desenho usando objetos especiais, que fornecem uma maneira de incorporar o código bruto de LaTeX e PSTricks. Adicionando isso ao tetraedro faz o truque. Aqui está o resultado. Há vários detalhes a serem observados aqui. Primeiro, a convenção de cotação para o código bruto é semelhante ao comando verbo LaTeX. O primeiro caractere de espaço não branco após especial é entendido como sendo o caractere de citação, neste caso. O texto em bruto continua até que esse caractere repita. Em segundo lugar, o argumento referências 1. 2. 3. E 4 referem-se a valores de ponto, vetor ou escalar na lista a seguir. Isso é semelhante à sintaxe de macro TeX. As projeções transformadas e bidimensionais desses pontos tridimensionais são substituídas na saída final. Uma referência de argumento da forma 1-2 é substituída pelo ângulo em graus do vetor bidimensional que conecta as projeções dos dois pontos de argumento respectivos, aqui 1 e 2. O ângulo substituído é encerrado em chaves. Quando a saída TikZ / PGF está sendo gerada, o ângulo é arredondado para o grau mais próximo porque ângulos não inteiros não são permitidos por primitivas TikZ / PGF. A partir da versão 0.3 do sketch. Argumentos especiais podem ser escalares ou vetores além de pontos. As referências a argumentos escalares são meramente substituídas por um número formatado como qualquer coordenada de ponto. As referências a vetores tornam-se pontos bidimensionais. O operador de carrapato que seleciona componentes individuais de pontos e vetores em outro lugar no esboço (veja, por exemplo, Aritmética Affine) também pode ser aplicado a referências de argumento de ponto e vetor. Todas as três dimensões de um ponto ou vetor transformado também podem ser substituídas por 3. Consulte Specials para detalhes. Por padrão, os objetos especiais são impressos por último, sobrepondo todos os outros objetos na cena. Se você especificar a opção interna layin. O algoritmo de superfície oculta considera o objeto especial inteiro como o primeiro ponto (1) na lista de argumentos. Se esse ponto está atrás (de menor z-componente do que) qualquer drawable, então todo o objeto especial é desenhado antes que o drawable, de modo que o drawable obscurece partes do objeto especial que se sobrepõe-lo. No nosso exemplo, p1 é o ponto mais frontal da cena (tem o maior componente z), portanto, adicionar Layin não tem efeito. Com opção layunder. Um especial é desenhado antes. Portanto, aparece sob qualquer um dos objetos manipulados pelo algoritmo de superfície oculta. Isto é como os eixos cinzentos claros foram adicionados ao mundo de ldquohello worldrdquo Olá mundo. Objetos especiais são poderosos, com muitos usos possíveis. 2.5 Transforma Agora vamos adicionar uma segunda cópia do tetraedro perfurado. Bem girar a cópia de 90 graus sobre o eixo x com a origem como centro de rotação para que possamos ver a parte traseira, em seguida, traduzi-lo para o rightmdashin o positivo x-directionmdashso ele doesnt colidir com o original. Para nos ajudar a ver o que está acontecendo, faça a parte de trás cinza. Aqui o código inteiro do exemplo anterior foi envolvido em uma definição formando um bloco com chaves (um único item não precisaria deles). As definições de ponto aninhadas dentro das chaves são lexicamente escopo. Seu significado se estende até o final do bloco. O def externo é chamado uma definição drawable porque descreve algo que pode ser desenhado. Uma definição extraível por si só não faz acontecer nada até que seu nome seja referenciado. As refer�cias desenh�eis devem ser inclu�as em chaves, v. g. . Sem espaço em branco. No código acima, a primeira referência é simples. Seu efeito é meramente duplicar o desenho anterior. Quase qualquer série de comandos de esboço coisas podem ser substituídos por def foo sem alterar o seu significado. O comando put fornece uma segunda referência, desta vez com uma transformada aplicada primeiro. A rotação transformar transforma o tetraedro 90 graus sobre a origem. O eixo de rotação é o vetor 1,0,0. Pela regra da mão direita. Isso faz com que a parte superior do tetraedro para girar em direção ao espectador eo fundo de distância. A regra recebe seu nome a partir da seguinte definição: Direita mão regra. Se a mão direita é enrolada em torno de qualquer eixo com o polegar apontando na direção do eixo, então os dedos se enrolam na direção da rotação positiva em torno desse eixo. A translate transform move a pirâmide lateralmente para a direita, adicionando o vetor 2,5,0,0 a cada coordenada de vértice. O resultado é mostrado aqui. 2.6 Objetos repetidos Para desenhar sete instâncias do tetraedro, cada uma diferindo da última pela mesma transformada, substitua os dois últimos comandos do exemplo anterior com E o resultado. 2.7 Objetos varridos Muitas formas familiares podem ser geradas varrendo as mais simples através do espaço e considerando o caminho, a superfície ou o volume resultante. Sketch implementa essa idéia no comando sweep. Este código varre o ponto (1,0,0) oito vezes girando 180/8 22,5 graus cada vez e conectando os pontos resultantes com segmentos de linha. O def usado aqui é uma definição escalar. As referências aos escalares não têm nenhum parênteses. Varredura de pontos. Pontos varridos fazem linhas e polígonos. Polyline varre. Linhas varridas fazem superfícies. Varredura aninhada. As varreduras varridas são varreduras úteis do polígono. Os polígonos varridos produzem sólidos. Polyline varre com fechamento. E assim fazem varreduras fechadas da polilinha. Affine aritmética. Esboço expressão matemática útil. Mais para aprender. Confira a tira Mobius 2.7.1 Varredura de pontos Varrer um ponto faz um caminho unidimensional, que é uma polilinha. Como temos varrido com uma rotação, o resultado é um arco circular. Aqui está o que parece. Este é o primeiro exemplo que vimos da aritmética do esboço. A expressão 180 / nsegs faz com que as oito rotações para adicionar a 180. Se você está prestando atenção, você já observou que há nove pontos, produzindo oito segmentos de linha. Você pode fazer com que o ponto de varredura gere um único polígono em vez de uma polilinha usando a tag de fechamento lt após o número de objetos varridos. Código e resultado seguir 2.7.2 Varreduras de polilinhas Varrer uma polilinha produz uma superfície composta de muitas faces. A hélice ininterrupta no exemplo Helix com cull set false então true é produzida por este código (mais uma rotação de colocação circundante para fazer uma visão interessante que foi omitida). Novamente, 60 segmentos da hélice são produzidos conectando 61 instâncias da linha varrida. Opções aplicadas à varredura, aqui cullfalse. São tratadas como opções para o polígono ou polilinha gerados. Opções da linha varrida em si, aqui linewidth2pt. São ignorados, embora com um aviso. Esta def é uma definição de vector, que deve ser referenciada com colchetes, e. Foo. 2.7.3 Varredura aninhada Quando o ponto central de rotação é omitido, a origem é assumida. Quando um ponto tem apenas duas coordenadas, elas são tomadas como xey, com z0 assumido. Obtém-se assim um toróide com este código. Para a intuição, a idéia do código é desenhar um círculo à direita da origem no plano xy, então gire esse círculo ldquoout do planerdquo sobre o eixo y para fazer a figura final. Isso produz o seguinte. (Uma rotação de visualização e alguns eixos foram adicionados.) Este exemplo também mostra que o objeto varrido pode ser ele próprio uma outra varredura. Na verdade, pode ser qualquer expressão de esboço que resulta em uma lista de um ou mais pontos ou, alternativamente, uma lista de uma ou mais polilinhas e polígonos. O último tipo de lista pode ser criado com um bloco bloqueado, talvez depois de um put ou repeat. 2.7.4 Varredura de polígonos Varrer um polígono cria uma superfície fechada com polígonos nas extremidades, que são apenas cópias do original, adequadamente posicionadas. Consulte Exemplo de bobina sólida. As opções no polígono varrido, se existirem, são aplicadas às extremidades. Caso contrário, as opções de varredura são usadas em todo. 2.7.5 Varredura de polilinha com fechamento Uma varredura de polilinha com uma marca de fecho cria outro tipo de superfície fechada. Primeiro, os segmentos de polilinha são conectados por faces, assim como sem a marca de fecho. Em seguida, cada conjunto de pontos finais é unido para fazer um polígono, um para cada extremidade. Segue-se um código para várias vistas de um prisma cilíndrico. Produz este desenho. As opções da linha varrida, se houver, são aplicadas às faces produzidas varrendo a linha, mas não os polígonos finais. Caso contrário, as opções de varredura serão aplicadas por toda parte. O def neste exemplo é uma definição de opção. As referências a opções devem ser incluídas entre colchetes, p. Foo. Você pode concatenar vários conjuntos de opções com uma única referência, p. Cor, tamanho, estilo faria com que as definições de opção de cor. tamanho. E estilo para aparecer em seqüência na saída criada pelo comando sketch contendo a referência. Felizmente, a sintaxe do sketch é tal que as referências de opções nunca podem ser confundidas com referências vetoriais. Embora não aparente neste exemplo, as referências de opções são úteis ao definir muitos objetos com uma aparência semelhante. 2.7.6 Aritmética afim A aritmética I 2.1 acima sugere uma verdade maior. Os operadores de esboço trabalham em escalares, vetores, pontos e transforma de acordo com as regras gerais da álgebra afim. Isso pode ser útil para configurar diagramas com geometria calculada. Por exemplo, se você tem vértices de triângulo (p1) a (p3) e precisa desenhar uma unidade de vetor normal apontando para fora do centro do triângulo, este código faz o truque. A primeira linha calcula o produto cruzado de dois vetores de borda do triângulo e o dimensiona para o comprimento da unidade. O segundo calcula a média dos vértices. Note que a subtração ea adição da origem efetivamente convertem vetores em pontos e vice-versa. O comando de linha desenha o normal no local correto. Duas advertências a respeito deste exemplo permanecem. Primeiro, a única maneira de usar as setas do estilo PSTricks é com setas. A sintaxe alternativa para setas PSTricks não é permitida no sketch. Em segundo lugar, você pode querer eliminar a terceira def e escrever em vez disso o seguinte. Isso não é permitido. As listas de pontos em drawables podem consistir apenas em pontos explícitos ou referências de pontos. No entanto, você pode usar a aritmética para calcular componentes pontuais. O seguinte funciona, embora seja um pouco pesado. Obviamente, o operador tick x extrai componentes de pontos e vetores. 2.7.7 Mais para aprender Este não é o fim da história sobre varreduras Convidamos o leitor para o corpo principal desta documentação Varre para aprender mais. Quem sabe onde terminará? 3 Idioma de entrada Este capítulo descreve o idioma de introdução do esboço em detalhe. Noções básicas de idiomas. Caso, espaço, comentários, incluir arquivos. Drawables. Coisas que podem ser desenhadas. Definições. Dando nomes às coisas. Ambiente global. Afetar todo o desenho. 3.1 Noções básicas A entrada de esboço é texto ASCII simples, geralmente armazenado em um arquivo de entrada. Ele descreve uma cena. Então a linguagem de esboço é uma linguagem de descrição de cena. A entrada do esboço também é declarativa. Ele simplesmente declara como a cena deve ser quando o desenho estiver completo e diz muito pouco sobre como o esboço deve fazer seu trabalho. Os comandos de esboço não são executados seqüencialmente como na linguagem de programação usual. Apenas contribuem para essa declaração. Alguns detalhes sintáticos são importantes. O caso é significativo na linguagem do esboço. Com algumas exceções, o espaço em branco não é. Isso inclui quebras de linha. Os comentários começam com ou e estendem até o fim da linha. Você pode desabilitar um pedaço de código de esboço sintaticamente correto ao incluí-lo em uma def. Existe um mecanismo simples de filderdquo ldquoinclude. O comando faz com que o conteúdo de otherfile. sk seja inserido como se eles fossem parte do arquivo atual. Identificadores. Nomes para as coisas. Palavras chave e reservadas. Nomes que você não deve usar. Literais. Constantes e construtores. Aritmética. Regras para expressões. Opções. Modificando a aparência do objeto. 3.1.1 Identificadores Os identificadores em sketch são referências a opções definidas anteriormente, escalares, pontos, vetores, transformações, drawables e tags. As Definições são explicadas em Definições. Um identificador consiste em uma letra inicial seguida de letras, números e sublinhados. O último caractere pode não ser um sublinhado. As palavras-chave não podem ser usadas como identificadores e as palavras reservadas devem ser evitadas. Consulte Chave e palavras reservadas. 3.1.2 Palavra chave e palavras reservadas As palavras-chave do esboço são picturebox curva def pontos quadro global entrada linha polígono colocar repetir definir varredura e depois. O analisador de esboço irá anotar um erro de sintaxe se algum destes for usado no lugar de um identificador apropriado. Além disso, existem palavras reservadas que podem atualmente ser definidas pelo usuário, mas com o risco de futuras versões do sketch rejeitarem essas definições. As palavras reservadas são acos asin atan2 cos inverso perspectiva projeto rotação escala sin especial sqrt traduzir unidade e ver. 3.1.3 Literais Literais no esboço incluem escalares, pontos, vetores e transformações. Literais, juntamente com referências de objeto definido, são usados em expressões aritméticas. Veja Aritmética. Literais escalares. Apenas os números. Literais ponto e vetor. Quantidades 3d. Transform literals. Matriz. 3.1.3.1 Literais escalares Literais escalares são números de ponto flutuante positivos com sintaxe de acordo com as convenções C. Seguem-se alguns exemplos. Literais escalares não podem conter espaços incorporados. 3.1.3.2 Literais pontuais e vetoriais Os pontos e literais vetoriais possuem essas formas, respectivamente. Cada um dos componentes é em si uma expressão escalar. Os componentes z são opcionais e padrão para zero. 3.1.3.3 Transformar literais A maioria dos literais transformados são formados por construtores. Estes são resumidos na seguinte tabela. Todas as operações são associativas à esquerda, exceto para. Parênteses () são usados para agrupar para substituir precedência da maneira usual. Como você pode ver, o operador ponto. É geralmente um sinônimo para multiplicação run-of-the-mill,. Os significados diferem apenas para operandos vetoriais. O operador então simplesmente inverte a ordem do operando com respeito à multiplicação normal. A intenção aqui é fazer com que as composições sejam lidas mais naturalmente. O código expressa uma série de modificações sucessivas ao ponto, enquanto a forma equivalente será intuitiva apenas para matemáticos (e talvez leitores de língua árabe). 3.1.4.2 Formas unárias As formas unárias ou de um operando são resumidas na tabela a seguir, onde X representa o operando. Negação escalar unária. Negação unária do vetor. Unidade vetor com o mesmo sentido. Raiz quadrada escalar. Seno trigonométrico (X em graus). Cosseno trigonométrico (X em graus). Seno inverso (X em graus). Coseno inverso (X em graus). Ângulo polar em graus do vetor X, Y. Erros são relatados quando X. unidade. como em. Acos. Sqrt Atan2. E falha inversa devido a operandos fora de seus respectivos domínios. 3.1.5 Opções As opções são usadas para especificar detalhes da aparência de drawables. Como mostrado acima, eles são dados como pares chave-valor separados por vírgulas. PSTricks opções. Opções herdadas de PSTricks. TikZ / PGF opções. Opções herdadas de TikZ / PGF. Pontos em TikZ / PGF. Sketch usa círculos TikZ / PGF para pontos. TikZ / PGF estilos definidos pelo usuário. Suporte para TikZ / PGF nomeado, estilos definidos pelo usuário. Transparência. Ver-através de polígonos. Opções internas. Opções usadas pelo sketch. 3.1.5.1 Opções de PSTricks Quando o idioma pstricks é selecionado (o padrão), os pares de valores-chave permitidos incluem todos aqueles para objetos PSTricks similares. Por exemplo, um polígono pode ter as opções Esboço apenas passa essas para PSTricks sem verificação ou modificação. As listas de opções são sempre opcionais. Uma lista de opções em falta é equivalente a uma lista vazia. Quando um polígono tem opções para a face e as bordas e o polígono é dividido pelo algoritmo da superfície oculta, o sketch deve copiar as opções de aresta para psline s para os segmentos de aresta e as opções de face para pspolygon s. As opções conhecidas para esboçar para fins desta operação de divisão incluem setas. traço. Dotsep. Preencher Fillstyle. Linecolor. Linestyle. espessura da linha. opacidade. Showpoints. Acidente vascular cerebral. E transpalpha. 3.1.5.2 Opções de TikZ / PGF As opções de TikZ / PGF são tratadas da mesma forma que para PSTricks. Embora TikZ / PGF freqüentemente permite que cores e estilos sejam fornecidos sem chaves correspondentes, por exemplo, isso não é permitido no sketch. Para desenhar uma linha vermelha, ultra-grossa em esboço. O formulário é apenas como para PSTricks. Quando um polígono tem opções para sua face e suas bordas e o polígono é dividido pelo algoritmo da superfície oculta, o sketch deve copiar as opções de aresta para psline s para os segmentos de aresta e as opções de face para pspolygon s. As opções TikZ / PGF conhecidas para esboçar para efeitos desta operação de divisão incluem setas. boné. cor. Traço padrão. Dash fase. duplo. Dupla distância. desenhar. Desenhar opacidade. preencher. Opacidade de preenchimento. Junte-se. espessura da linha. Limite da mitra. padrão. Cor do teste padrão. E estilo. A opção de estilo pode conter informações de face e borda, de modo que o sketch deve verificar o valor do estilo. Os valores conhecidos para o esboço incluem tracejado. Densamente tracejado. Densamente pontilhada. pontilhado. duplo. Frouxamente tracejado. Vagamente pontilhada. Quase opaco. Quase transparente. Semítico semitransparente. sólido. Grosso. fino. transparente. Ultra quase transparente. Ultra grossa. ultra fino. very nearly transparent. very thick. and very thin. 3.1.5.3 Dots in TikZ/PGF TikZ/PGF does not have a dots command as does PSTricks. Instead, Sketch emits dots as filldraw circles. The diameter may be set using the option dotsize borrowed from PSTricks. The dotsize option will be removed from the option list in the output filldraw command. Other options work in the expected way. For example, fill sets fill color and color sets line color of the circles. 3.1.5.4 TikZ/PGF user-defined styles TikZ/PGF allows named styles defined by the user, for example Since sketch has no information on the contents of such styles, it omits them entirely from lines, polygons, and their edges during option splitting. For example, produces the TikZ output Note that the user-defined styles are not present. Sketch also issues warnings: The remedy is to state explicitly whether a user-defined style should be attched to polygons or lines in the TikZ output using pseudo-options fill style and line style. Now, the output is A useful technique is to include user-defined style definitions in sketch code as special s with option layunder to ensure that the styles are emitted first in the output, before any uses of the style names. 2 For example, The author is responsible for using the key, line style or fill style. that matches the content of the style definition. 3.1.5.5 Transparency Both PSTricks and TikZ/PGF support polygon options that have the effect of making the polygon appear transparent. For PSTricks. keyword transpalpha was used during initial development of transparency features, and opacity was adopted later. Sketch honors both. TikZ/PGF uses opacity only. When transparent polygons are in the foreground, objects behind them (drawn earlier) are visible with color subdued and tinted. The hidden surface algorithm of sketch works well with such transparent polygons. Note that cullfalse must be used for rear-facing polygons to be visible when positioned behind other transparent surfaces. 3.1.5.6 Internal options There are also internal options used only by sketch and not passed on to PSTricks. These are summarized in the following table. This command is the three-dimensional equivalent of the PSTricks command pscurve. It is not implemented in the current version of sketch. 3.2.4 Polygons This command is the three-dimensional equivalent of the PSTricks command pspolygon. The sketch hidden surface algorithm assumes that polygons are convex and planar. In practice, drawings may well turn out correctly even if these assumptions are violated. 3.2.5 Specials Here can be any character and is used to delimit the start and end of rawtext. The command embeds rawtext in the sketch output after performing substitutions as follows. i where i is a positive integer is replaced by the i th value in arglist. Point and vector arguments become two-dimensional points, which are the transformed 3d arguments projected onto the x - y plane. This allows two-dimentional output elements such as labels to be easily positioned with respect to three-dimensional features in the drawing. Scalar arguments are subsituted directly. No transformation is applied. is also replaced as above. i 2 is replaced as above for points or vectors. It is an error for the i th argument to be a scalar. i x. i y. or i z is replaced, respectively, by the scalar x. y. or z - coordinate of the argument point or vector. It is an error for the i th argument to be a scalar. i 3 is replaced by the three-dimensional transformed argument. Note that if a perspective transformation has been applied, the z - coordinate has little geometric significance, though it accurately indicates relative depth. i - j where i and j are positive integers is replaced by a string where angle is the polar angle of a vector from the i th point in pointlist to the j th point projected into the x-y plane. It is an error for the i th or j th argument to be a scalar or a vector. is also replaced as above. is replaced with . The forms with braces are useful when the argument is immediately followed by a digit or a tick character that is part of the TeX code. The only useful option of special is lay. which determines if the substitued raw text is emitted before, after, or using the first point in pointlist as an indicator of depth. These occur, respectively, with layunder. layover. and layin. See Special objects and TikZ/PGF user-defined styles for examples. See Internal options. 3.2.6 Sweeps The sweep connects n (or perhaps n 1) copies of sweptobject in order to create a new object of higher dimension. The Ti (for i between 1 and r) are transforms. The kth copy of sweptobject is produced by applying the following transform to the original. Here T k means ldquotransform T applied k times. rdquo The original object is the zeroth copy, with k0 and effectively no transform applied (T0I, the identity transform). The method of connecting the copies depends on the type of sweptobject and on whether the closure tag ltgt is present or not. An example of a sweep where r2 is the Mobius figure at More to learn. Swept points. Swept points make lines or polygons. Swept lines. Swept lines make open or closed surfaces. Swept polygons. Swept polygons make closed surfaces. Swept blocks. Swept block block of sweeps. Sweep face splitting. Fixing warped faces with triangles. 3.2.6.1 Swept points If sweptobject is a point list and there is no closure tag, then sweep connects n 1 successive copies of each point (including the original) with straight line segments to form a polyline. If there are m points in the original point list, then m polylines with n segments each are formed by the sweep. In this manner, sweep forms a set of one-dimensional objects (polylines) from zero-dimensional ones (points). When there is a closure tag, sweep connects n successive copies of each point (including the original) with straight line segments and finally connects the last copy back to the original to form a polygon with n sides. If there are m points in the original point list, then m polygons with n sides each are formed by the sweep. In this manner, sweep forms a set of two-dimensional objects (polygons) from zero-dimensional ones (points). Options of the sweep are copied directly to the resulting polyline(s). 3.2.6.2 Swept lines If sweptobject is a polyline and there is no closure tag, then sweep connects n 1 successive copies of the polyline (including the original) with four-sided polygons, each pair of copies giving rise to a ldquopolygon strip. rdquo If there are m points in the original polyline, then (m-1) n polygons are formed by the sweep. We call these body polygons. In this manner, sweep forms a two-dimensional surface from from a one-dimensional polyline. The order of vertices produced by sweep is important. If a polygons vertices do not appear in counter-clockwise order in the final image, the polygon will be culled (unless cullfalse is set). If the points in the kth copy of the polyline are P1, P2, . . Pm, and the points in the next copy, the (k1)st, are P1, P2, . . Pm, then the vertex order of the generated polygons is Options of unclosed line sweeps are copied to each output polygon. Options of the swept line are ignored. When there is a closure tag, then sweep connects n successive copies of the polyline (including the original) with four-sided body polygons just as the case with no closure tag. It then connects the last copy back to the original to form a ribbon-shaped surface that closes on itself with two holes remaining. Finally, the sweep adds two more polygons to seal the holes and form a closed surface that, depending on the sweep transforms, may represent the boundary of a solid. In this manner, sweep forms the boundary of a three-dimensional object from a one-dimensional polyline. We call these hole-filling polygons ends. The order of vertices of end polygons is important for correct culling as described above. If P11, P12, . . P1n are the n copies of the first polyline point and Pm1, Pm2, .,Pmn are the n copies of the last polyline point, then the end polygon vertex order is If there are no options on the swept line, then the sweep options are copied to each output polygon. If the swept line does have options, these are copied to corresponding body polygons the sweep options are copied to the end polygons. In this manner, body and ends may be drawn with different characteristics such as fillcolor. 3.2.6.3 Swept polygons If sweptobject is a polygon, the sweep connects n 1 successive copies of the closed polyline border of the polygon to form body polygons exactly as though the border were a swept polyline as described in Swept lines. If there are m points in the original polygon, then m n body polygons are formed by this sweep. The body polygons form an extrusion of the boundary of the original polygon with two holes at the open ends. Finally, the sweep adds two copies of the original polygon to cover the holes. We call these hole-filling polygons ends. In this manner, sweep forms the boundary of a three-dimensional object from a two-dimensional polygon. The order of vertices of end polygons is important for correct culling as described above. An exact copy of the original polygon with vertex order intact forms the first end polygon. The other end polygon results from transforming and the reversing the order of vertices in the original. The transform places the original polygon at the uncovered hole it is If there are no options on the swept polygon, then the sweep options are copied to each output polygon. If the swept polygon does have options, these are copied to the ends the sweep options are copied to the body polygons. In this manner, body and ends may be drawn with different characteristics such as fillcolor. 3.2.6.4 Swept blocks The swept object sweptobject may also be any collection of polylines and polygons. This may be a block composed of line and/or polygon commands in braces . or it may be the result of a repeat. another sweep. etc. The sweep acts independently on each object in the block exactly as if it were a single swept object described above in Swept lines and Swept polygons. 3.2.6.5 Sweep face splitting Before sending each four-sided body polygon of a sweep to the output, sketch tests to see if it is roughly planar. Since planarity is necessary for proper functioning of the hidden surface algorithm, ldquowarpedrdquo polygons are automatically split into two triangles. Hole-filling polygons produced by closure-tagged line sweeps are not split. Nor are original polygons in polygon sweeps. It is the users responsibility to ensure these are planar. 3.2.7 Blocks Any sequence of drawables may be grouped in a block merely by enclosing them in braces . A block is itself drawable. A key use of blocks is to extend the effect of a single def. Definitions. put Puts. sweep Sweeps. or repeat Repeats to include several objects rather than one. Definitions (See Definitions .) inside a block have lexical scope extending from the place of definition to the end of the block. 3.2.8 Repeats The repeat makes n transformed copies of repeatedobject (including the original). The Ti are transforms. The kth copy of the repeatedobject (for k0,1. n-1) is produced in the same manner as for sweep s described in Sweeps. This is repeated here (no pun intended) for convenience. To make the kth copy, the following transform is applied to the original object. Here T k means ldquotransform T applied k times. rdquo 3.2.9 Puts Put merely applies transform T to the drawable putobject. 3.3 Definitions Definitions give names to sketch objects. Definitions alone are benign. A sketch input file consisting entirely of definitions will generate no drawing. Only when definitions are referenced do they potentially lead to ink on the drawing. The intent of definitions is to make sketch code more concise and readable. There is no input file employing definitions that could not be re-written without them. Definable objects include any result of an affine arithmetic expression (scalar, point, vector, or transform), any drawable object (dots, line, curve, polygon, block, sweep, put, repeat, or special), and option strings. In addition, tag definitions. which have no associated object at all, allow the meaning of other definitions to be selected from a set of alternatives. Since tags may be defined (and undefined) in the command line of sketch. they can be an aid in the script-driven preparation of documents. Forms of definitions. Different defs for different purposes. Forms of references. How references denote types. 3.3.1 Forms of definitions Definitions have three possible forms, simple. with alternatives. and tag as shown here in order. The simple definition merely associates object with the identifier id. The definition with alternatives associates objecti with id. where tagi is the first defined tag in the list of alternative tag references. If no tag in the list is defined, then defaultobject is associated with identifier id. The final form defines id as a tag. Another way to define a tag is with the - D command line option. See Command line. 3.3.2 Forms of references References to defined names are enclosed in bracketing delimiters. The delimiter characters imply the type of the associated value as shown in the table below. A type error is raised if the type of a reference does not match the type of the defined value. The intent of this mechanism is, again, to make sketch input files more readable. Note that square brackets are used both for vector and for options references. Details of sketch syntax make it impossible for these two reference types to be confused. The special multiple reference id1. id2. idN acts as if the respective lists of options were concatenated. 3.4 Global environment An optional global environment block provides a few ways to affect the entire scene. The block must appear as the last text in the sketch input file. It may include definitions, but note that previous definitions at the top level (not nested inside blocks) are also available. The contents of environmentsettings are discussed in the sections that follow. Global options. Attributes of the entire drawing. Camera. A final camera transformation of the scene. Picture box. Setting the bounding box and 2d clipping. Frame. Adding a box around the drawing. Language. Setting the output language. 3.4.1 Global options The contents of options. except for sketch internal options, are copied as-is to a psset that appears before anything else in the output file. This is a good place to set unit. a default linewidth. etc. Internal options work on all objects where they make sense. This includes cull and split (but not lay ). See Internal options. 3.4.2 Camera The transformexpression is applied after all other transformations of the scene. This is currently only useful for transforming the bounding box. See Picture box. It will play a role in any future implementation of clipping. 3.4.3 Picture box The first form of picturebox causes a scalar baseline fraction to be emitted in the pspicture environment of the output. See PSTricks documentation for pspicture. In the second form, the baseline fraction is optional, and the two points that follow define the diagonal of a three-dimensional bounding box for the completed scene. The parallel projection of the bounding box determines the corners of the drawings pspicture environment, which is used in place of pspicture. This causes PostScript to clip the final drawing to the bounding box in 2d. If there is a camera specified, the camera tranformation is applied to the bounding box, and the pspicture is set just large enough to include the transformed box. When no bounding box is given, sketch computes one automatically. 3.4.4 Frame Causes a psframebox to surround the pspicture environment in the output. If options are present, they are copied as-is. Normally one would want to set linewidth. linestyle. linecolor. etc. If omitted, then framesep0pt is added so that the frame tightly hugs the pspicture. 3.4.5 Language Sets the output language generated by sketch. The set of options understood by sketch also changes. For example, the PSTricks option linewidth will not be properly handled if language is set to tikz. Similarly, the TikZ option line style (note the space) will not be properly handled if language is set to pstricks. If no language is specified, the default pstricks is used. An optional comma followed by latex or context specifies the macro package that the output should assume. This affects the picture environment commands emitted and the document template used with the - T option. See Command line. Note that at the time this manual was generated, PSTricks was not supported by LaTeX or by ConTeXt. 4 Building a drawing Successful drawings with sketch and with any scene description language require that the user develop an accurate mental picture of her code and its meaning. This image is best built in small pieces. Therefore, sketch inputs are best created in small increments with frequent pauses to compile and view the results. Careful comments in the input often help as a scene grows in complexity. Overview. Building a substantial drawing. A technical drawing. An example with fine placement. A hierarchical model. An example with sweeps and puts. Caveats. Where trouble can occur. 4.1 Overview As an overview, lets develop a diagram that shows how a perspective projection transform works. Well start with the traditional reference object used in computer graphics textbooks, a house-shaped prism. Begin by defining the points of the house. Rather than defining the faces of the house as polygons and transforming those, we are going to transform the points themselves with sketch arithmetic so that we have names for the transformed points later. To add a door to the house, we use a polygon slightly in front of the foremost face of the house. Now lets create a new set of points that are a to-be-determined transform of the originals. Note the use of a transform definition and transform references. Now define the seven polygonal faces of the house and the door using the transformed points as vertices. Be careful with vertex order Time for a sanity check. Add the line and this is what we get. This is correct, but does not reveal very much. Common errors are misplaced vertices and polygons missing entirely due to incorrect vertex order. To rule these out, lets inspect all sides of the house. This is not hard. Merely replace the reference with a repeat. See Repeats. Again things look correct. Note that the hidden surface algorithm handles intersecting polygons correctly where some copies of the house overlap. Lets lay out the geometry of perspective projection of the house onto a plane with rays passing through the origin. Begin by positioning the house twelve units back on the negative z-axis and adding a set of coordinate axes. To move the house we need only change the ldquohouse positioningrdquo transform defined earlier. Time for another test. Lets build a real view transform, creating a virtual camera to look at the scene we are constructing. Replace the repeat with The view transform repositions the scene so that the point eye is at the origin and the direction from eye to lookat is the negative z-axis. This requires a rotation and a translation that are all packed into the constructor view. This is starting to look good Add the projection plane half way between the origin and the house at z-5. Well try the angle argument feature of special to position a label. Add to the list of objects in the put above. The way we constructed the points of the house now makes it easy to draw rays of projection. Well cast one ray from every visible vertex of the house and define options so the appearance of all rays can be changed at the same time. The result is shown here. The rays pierce the projection plane at the corresponding points on the perspective image we are trying to draw. Albrecht Duumlrer and his Renaissance contemporaries had the same idea in the early 1500s. All thats left is to find a way to connect the points of the house on the projection plane. We could pull out a good computer graphics text, find the necessary matrix, and enter it ourselves as a transform literal. See Transform literals. That work is already done, however. We can use the project(p) constructor. There are still some details that require care. Projection will flatten whatever is transformed onto the plane z-p. Therefore any part of the house could disappear behind the projection plane (the hidden surface algorithm orders objects at the same depth arbitrarily). The door may also disappear behind the front of the house. To make sure everything remains visible, well place the house a tiny bit in front of the projection plane and a second copy of the door in front of the house. If you have studied and understand all this, you are well on the way to success with sketch. Not shown are the 20 or so iterations that were required to find a reasonable viewing angle and house position, etc. Nonetheless, this drawing was completed in about an hour. While a GUI tool may have been a little faster, it is unlikely that a new drawing, itself a perspective projection of the scene, could be generated with two more minutes work Just change the view transform to and produce this. 4.2 A technical drawing Lets look at a drawing that represents the kind of problem sketch was meant to solvemdasha pair of textbook figures regarding a polygonal approximation of a truncated cone. Here are the pictures we will produce. The cone shape is just a swept line with no closure tag and culling turned off. Begin by setting up some useful constants. The points p0 and p1 are the end points of the line to be swept. The definition segrot is the sweep transformation. With these, the cone itself is simple. The axes are next and include an interesing trick that shows the hidden parts as dotted lines. The secret is draw the axes twicemdashsolid lines with the normal hidden surface algorithm in effect, and then dotted with the option layover so that no polygons can hide them. The labels are applied with PSTricks special objects as usual. For the height dimension mark, the power of affine arithetic is very helpful. The general idea employed here is to compute a unit ldquoreference vectorrdquo parallel to the xz-plane in the desired direction of the dimension from the origin. The transformation segrot2 rotates two segments about the y-axis. When applied to (p1) - (O). the resulting vector points to the right as shown. In this manner, we can pick any vertex as the location of the height dimension lines by varying the exponent of segrot. This is only one of many possible strategies. The computation of hm2 is a useful idiom for finding the centroid of a set of points. The two radius marks are done similarly, so we present the code without comment. The second drawing uses the same techniques. Only the method for drawing the elliptical arc is new. Here is the code. We could have swept a point to make the arc with sketch. but using a PSTricks custom graphic was simpler. Again we computed the centroid of the quadrilateral by averaging points. Note that scaling in Postscript distorts the arrowhead, but in this case the distortion actually looks better in the projection of the slanted face. A sketch arrowhead would not have been distorted. The complete code for this example, which draws either figure depending on the definition of the tag ltlabeledgt. is included in the sketch distribution in the file truncatedcone. sk. 4.3 A hierarchical model While sketch was never meant to be a geometric modeling language, it comes fairly close. The following example puts all we have seen to work in a very simple model of the human hand. Start by sweeping a line to make a truncated cone, which will be copied over and over again to make the segments of fingers. In hand anatomy, distal is ldquoat the tiprdquo and proximal is ldquoin the area of the palm. rdquo We have omitted all the scalar constants. You can find them in hand. sk. which is provided in the sketch distribution. We also need a prototypical sphere to use for the joints themselves. Well now design the index finger (number 1 in our notational convention finger 0 is the thumb). The distal rotation for the finger applies only to the tip, so we define the following. The identifiers here are for size and location constants. The exception is distalrot1. This rotation parameter models the flexing of the finger tip. The first put makes a copy of the finger segment that is translated upward just far enough to make room for the spherical joint. Then it applies the distal rotation. Finally it translates the whole assembly upward again to make room for the middle phlanges (the next bone toward the palm). The second put positions the sphere. There is a rotation to place the grid on the sphere surface at an nice angle, then a translation to the base of the distal phlanges, which is also center of its rotation. Finally, the last put positions the middle segment itself. The middle joint is the next one down, with rotation angle middlerot1. When this angle changes, we need all the objects in distal1 to rotate as a unit. This is the reasoning behind the next definition. This looks very similar to the previous definition, and it is. The important difference is that rather than positioning and rotating a single segment, we position and rotate the entire ldquoassemblyrdquo defined as distal1. The rest is just arithmetic to compute sizes and positions that look nice. The last put places an appropriately shaped segment that is the proximal phlanges . the bone that joins the palm of the hand. This completes the finger itself. All the other fingers are described identically to this one. We account for the fact that real fingers are different sizes in the next step, which is to build the entire hand. The hand definition that follows includes a section for each finger. Well continue with finger 1 and omit all the others. (Of note is that the thumb needs slightly special treatmentmdashan extra rotation to account for its opposing angle. This is clear in the full source code.) Not surprisingly, the hand definition looks very much like the previous two. It should be no surprise that when the rotation parameter meta1rot changes, the entire finger rotates There is an additional rotation that allows the fingers to spread laterally. We say these joints of the proximal phlanges have two degrees of freedom . The joints higher on the finger have only one. Finally, each finger is scaled by a factor to lend it proportion. The last section of the definition creates the polytope for the palm of the hand by sweep ing a 10-sided polygon through a very short arc (9 degrees). This provides a wedge-shaped profile when viewed from the side. The thick end of the wedge is the wrist. Because the polygon is concave, it is split into into two convex shapes with nine and four vertices. We can now have fun positioning the hand by adjusting the various rotation angles. The complete source includes definitions with alternatives that include the following views and more. 4.4 Caveats Sketch is a fairly powerful tool for drawing, but, just as with TeX, the power to create beautiful results comes along with the power to make mistakes. The following are some points where care is necessary and where the current version of sketch is limited or has known bugs. Limits on error detection. What sketch doesnt do. Clipping. No clipping at present. Hidden surface removal. Imperfections to fix. 4.4.1 Limits on sketch error detection Sketch catches many kinds of errors, but not all. For example, options that sketch does not recognize, even incorrect ones, are quietly copied to PSTricks commands in the output. It is also unfortunately easy to produce sketch inputs that lead to no picture at all (improper vertex ordering causes everything to be culled), to pictures that are too big or too small for PSTricks to draw (due to limits of TeX math), and pictures that look nothing like what was intended. A picture with one of these problems can be difficult to ldquodebug. rdquo We offer the following suggestions. Follow the suggested incremental development method described in Overview. Always maintain one or two back-versions of a drawing so that it is easy to fall back to a known-good increment. When using perspective. ensure all finally transformed objects satisfy zlt0 and, in fact, do not come very close to the origin at all. Temporarily use cullfalse to see where vertex ordering problems lie. Use temporary changes of color of one or more objects to ensure that your understanding of the scene geometry is correct. If PSTricks complains about something, inspect the output directly for clues. 4.4.2 Clipping The current version of sketch has no clipping operations. The entire scene is always drawn. This means that when a perspective transform is employed, it is the users responsibility to make sure the entire scene remains in front of the viewer, the region zlt0. 4.4.3 Hidden surface removal and polygon splitting Sketch uses the depth sort algorithm for hidden surface removal. This is a very old technique due to Newell. 3 It is generally regarded as too slow for real time graphics, but it is ideal for our purpose where speed is not very important. 4 The depth sort algorithm merely sorts objects on a key of increasing z-coordinate, equivalent to decreasing depth. Objects are then drawn in the sorted sequence so that those at the rear of the scene are overwritten by those closer to the viewer. Since this is also how oil painters practice their art, depth sort is sometimes called ldquothe painters algorithm. rdquo In some cases it is impossible to strictly order polygons according to depth. Moreover, even if a correct depth ordering exists, the computation needed to find it may be too complex and slow. In these cases, sketch splits one or more polygons into pieces. The expectation is that the new, smaller polygons will be simpler to order. Sketch uses a BSP (binary space partition) to handle the splitting operation. Statistics. Performance numbers on depth sort. Bugs and anomalies. Imperfections in this implementation. 4.4.3.1 Statistics For the curious, sketch writes one line of depth sort statistics. Here is an example for a large collection of triangles. It means that 34,824 objects were depth sorted after culling. For each, an average of 581.9 others had to be checked to ensure that the initial, approximate ordering was correct. Among all these checks, only 5 resulted in swaps to reorder the initial sort. In two cases, a correct ordering could not be determined, so binary space partitions were constructed for splitting. A total of 4 objects (triangles in this case) were inserted in the partitions, and 6 polygons were produced. Finally, 24,851 ldquolast resortrdquo polygon overlap checks were performed after simpler, faster checks failed to yield conclusive results. The final /0 is for line-polygon overlap checks. For comparison, the statistics for the last figure in Overview follow. Note that there was proportionally much more swapping and splitting activity in this highly connected scene. 4.4.3.2 Bugs and anomalies Polygon and line splitting can both cause anomalies in the output. PSTricks dash patterns, specified with linestyledashed. can be disrupted by splitting. This occurs when the depth sort gives up too early and splits a line where it is not really necessary. A workaround is to use gray or finely dotted lines instead. If your drawing is small, you can also edit the sketch output by hand to merge the pieces of the offending line. Another anomaly is tiny (or in degenerate cases not-so-tiny) notches in the lines that border split polygons. These derive from the way each polygon is painted: first, all pixels within the boundary are filled with color (perhaps white), then the same boundary is stroked (a Postscript term) with a line. The result is that half the line lies inside the boundary and half outside, while the Painters algorithm assumes the polygon lies entirely within its boundary. The notches are due to one polygon fill operation overwriting the already-drawn inside of the border of another polygon. 5 One workaround is to make border lines very thin. In fact linewidth0pt is guaranteed to eliminate this problem, though this results in the thinnest line your output device can draw, which is usually too thin. You might get lucky by merely reordering things in the input file, which is likely to move the splits to different places. The only sure-fire solution is pretty terrible: custom fit special overlay lines (with psline ) to cover the notches. Polygon splitting also breaks PSTricks hatch patterns. The only known workaround is to substitute a solid fill for the hatch. 5 Command line Description Processes the sketch input files in order to produce PSTricks output code suitable for inclusion in a TeX or LaTeX document. Options: - h Print a short catalog of options. - V Set the PSTricks version assumed for output purposes to x. y. for example 1.19. Usually needed only if your PSTricks is old compared to your sketch. Use - v to see what sketch assumes by default. - v Print version information to standard output, including the version of PSTricks assumed for output (can be changed with - V above). - b Use a BSP (See Hidden surface removal .) for all hidden surface removal rather than the default, which is the depth sort algorithm with BSPs used only for cycle resolution. This may produce correct output in certain degenerate cases where the depth sort cannot, but it also leads to many gratuitous splits, hence more anomalies Bugs and anomalies and big output files. - d Run sketch s parser in debugging mode. This is primarily for development. - t Use contents of file doctmp as a document template in which to enclose PSTricks output code. The code is inserted in place of the first instance of the escape string SKETCHOUTPUT . - T Causes PSTricks output to be enclosed in default US document template text. Option - Tu is a synonym. Option - Te causes the Euro standard document template to be used. A p appended to any of these options causes the respective default PSTricks document template to be printed to standard output. An appended P is a synonym. An appended T causes the the TikZ/PGF template to be printed. An appended L prints the LaTeX version of the document template, a synonym for the default. A C prints the ConTeXt template. - o Use output. tex as the output file. The default is standard output. - D Define a tag for purposes of selecting definition alternatives. See Definitions. The definition applies for all input files that follow unless the tag is undefined with - U. inputi. sk Input files, read in the sequence they are given. - U Un-define a tag for purposes of selecting definition alternatives. 6 Building and installing sketch Sketch is so small that compiling by brute force is probably best. The following command ought to do the trick on any systems where gcc is installed. Make sure to first change current directories to the place where you have unpacked the sources. The. exe at the end is necessary for Windows systems. Drop it if your system is some version of Unix. Other C compilers ought to work as just as well. For example, is the correct command for many versions of MS Visual C. In the latest versions, Microsoft has deprecated the - o option and, by default, does not define the STDC macro. This causes problems with some versions of flex. bison. lex. and yacc. which are used to create the sketch scanner and parser. Its nearly always possible to find a set of options that compiles with no errors or warnings, and this means sketch is very likely to work correctly. For example, the Visual C 2005 Express Edition compiler (available free of charge from the Microsoft web site), flex version 2.5.4, and bison version 2.1 build error-free with For purists, there is also a makefile compatible with GNU make and gcc. The command will build the executable, including the rebuilding of the scanner and parser with flex and bison if you have changed sketch. l or sketch. y respectively. While not essential, building the manual is an excellent test of your sketch installation. To build this document in all its myriad forms (assuming you have the necessary conversion programs on your system), use The possibilities are listed in this following table. Linked web pages, one per node. All the required tools are included in the standard TeX Live distribution except that an additional open source program epstool is needed to refine the Encapsulated Postscript bounding boxes of sketch - generated figures in the manual. This tool is available in binary form for Windows, and it builds easily with a simple make under linux or Cygwin installations that have development tools installed or under Mac OS X with XCode installed. Index of syntax Index of concepts 1 Or for European users of A4 size paper, - Te . 2 This clever trick is due to Kjell Magne Fauske. 3 Newell, M. E. R. G. Newell, and T. L. Sancha, A solution to the hidden surface problem. Proceedings of the ACM annual conference - Volume 1 . page 443ndash450, ACM Press, 1972. 4 We have run sketch on the famous Stanford Bunny, which consists of nearly 70,000 triangles. Run time was about 6 seconds. Most of this was spent writing the output file rather than in the hidden surface algorithm. LaTeX took much longer to process the resulting PSTricks code. The obvious conclusion is that the speed of the depth sort algorithm is not a worry. 5 I know how to fix this problem, but I dont like my solution, and Im interested in yours. Hi Luciano, and welcome to the Dev Forums Im guessing you wanted to raise b to the c power. If you are coding in C, the statement you want is: New C programmers are often surprised theres no exponentiation operator in the language. For doc on pow() and other math functions in the C runtime library, type man math at the prompt in the Terminal window of your Mac, or any Unix or Linux terminal. - Ray Yes I think Ray hit the nail on the head. It looks as if you wanted to perform and exponentiation operation, not a bitwise operation. So, just to expand on Rays answer a bit, the carrot symbol () that you used in your statement is, in C, the bitwise XOR operator, and has nothing to do with exponentiation. There are numerous bitwise operators in C (bitwise AND (amp), bitwise OR (), bitwise XOR ()), and they all deal with manipulating bits of data. If you were, in fact, trying to raising b to the power of c and assign that value back to a . then Rays post was the perfect answer as to how to do that. Many programmers that are new to C, especially ones coming from a language such as Visual Basic, where the carrot symbol is used for exponentiation operations, naturally try to use the same symbol for the same purpose in C, and are surprised to find that it doesnt do what they expected (understandably). As mentioned, this is because, in C, there is no exponentiation operator, and the carrot symbol does something completely different and unrelated to exponentiation. However, C does provide a predefined function in its standard library for exponentiation, and it is called the pow() function, which takes two double-typed arguments (the first is the number being risen and the second is the power that it is being raised to), and returns the result as a double. To use this function, all you have to do is write an include directive at the top of the file that you will be using the function in that tells the preprocessor to include the file math. h . See RayNewbs post for a solid example of how all this stuff would look in your source code, and, as he mentioned, open your Terminal and type in man math or, for this particular function, man pow to find out more about how this function works (you can page through the information with the spacebar or scroll down with the down arrow). Hope this was of some help for you, and best of luck with everything Q. Invalid operands to binary (have double and double)
Comments
Post a Comment