repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
jheckjr/recipe-box2
src/app/app.component.ts
import { Component, Inject } from '@angular/core'; import { AppStore } from './app-store'; import { addRecipe } from './actions'; import { RecipeState } from './reducers/recipe-reducer'; import { Recipe } from './models'; import { RecipeListComponent } from './recipe-list/recipe-list.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Recipe Box'; subtitle = 'A place to store all your favorite recipes!'; constructor( @Inject(AppStore) private store) { // Initialize state store.dispatch(addRecipe(null)); } }
jheckjr/recipe-box2
src/app/models/sample-recipe.ts
<reponame>jheckjr/recipe-box2 import { Recipe } from './recipe.model'; export const sampleRecipe: Recipe = { name: 'Oatmeal', ingredients: [ '1 pkt. oatmeal', '2/3 cup milk' ] };
jheckjr/recipe-box2
src/app/actions/user-control.ts
<reponame>jheckjr/recipe-box2 export enum UserControl { View, Add, Edit }
jheckjr/recipe-box2
src/app/local-storage-helper/local-storage-helper.spec.ts
<gh_stars>0 import { testRecipes } from '../recipe-list/test/test-recipes'; import { Recipe } from '../models'; import { RecipeEntities } from '../reducers/recipe-reducer'; import { getAllStoredRecipes, getAllStoredRecipeNames } from './local-storage-helper'; describe('Local Storage:', () => { beforeEach(() => { localStorage.clear(); testRecipes.forEach((recipe: Recipe) => { localStorage.setItem(recipe.name, JSON.stringify(recipe)); }); }); it('should get all stored recipes', () => { let recipes: RecipeEntities = getAllStoredRecipes(); testRecipes.forEach((recipe: Recipe) => { expect(recipes[recipe.name]).toEqual(recipe); }); }); it('should get no recipes when none stored', () => { localStorage.clear(); let recipes: RecipeEntities = getAllStoredRecipes(); expect(recipes).toEqual({}); }); it('should get all stored recipe names', () => { let recipeNames: string[] = getAllStoredRecipeNames(); expect(recipeNames.length).toEqual(testRecipes.length); testRecipes.forEach((recipe: Recipe) => { expect(recipeNames).toContain(recipe.name); }); }); it('should get no recipe name when none stored', () => { localStorage.clear(); let recipeNames: string[] = getAllStoredRecipeNames(); expect(recipeNames.length).toEqual(0); }); });
jheckjr/recipe-box2
src/app/recipe-edit/recipe-edit.component.ts
<gh_stars>0 import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { FormGroup, FormBuilder, FormArray, FormControl, Validators } from '@angular/forms'; import { Recipe, RecipeItemEvent, RecipeItemEventType } from '../models'; @Component({ selector: 'app-recipe-edit', templateUrl: './recipe-edit.component.html', styleUrls: ['./recipe-edit.component.css'] }) export class RecipeEditComponent implements OnInit { @Input() recipe: Recipe; @Output() buttonClicked: EventEmitter<RecipeItemEvent>; formGroup: FormGroup; constructor(private _fb: FormBuilder) { this.buttonClicked = new EventEmitter<RecipeItemEvent>(); } ngOnInit() { let recipeName = ''; if (this.recipe) { recipeName = this.recipe.name; } this.formGroup = this._fb.group({ name: [recipeName, [Validators.required]], ingredients: this._fb.array(this.initIngredients()) }); } /* Add FormControl array of ingredients if recipe exists or an array with an * empty FormControl otherwise */ initIngredients(): any[] { if (this.recipe) { return this.recipe.ingredients.map((ingredient) => { return this._fb.control(ingredient, Validators.required); }); } else { return [this._fb.control('', Validators.required)]; } } addIngredient() { const controlArray = <FormArray>this.formGroup.controls['ingredients']; controlArray.push(this._fb.control('', Validators.required)); } removeIngredient(idx: number) { const controlArray = <FormArray>this.formGroup.controls['ingredients']; if (controlArray.length > 1) { controlArray.removeAt(idx); } } saveRecipe(form: any) { let newRecipe: Recipe = { name: form.controls['name'].value, ingredients: (<FormArray>form.controls['ingredients']).controls .map((formControl) => { return formControl.value; }) }; let saveEvent: RecipeItemEvent = { eventType: RecipeItemEventType.Save, recipe: newRecipe }; this.recipe = null; this.ngOnInit(); this.buttonClicked.emit(saveEvent); } cancelClicked(event: any) { let cancelEvent: RecipeItemEvent = { eventType: RecipeItemEventType.Cancel, recipe: null }; this.recipe = null; this.ngOnInit(); this.buttonClicked.emit(cancelEvent); } }
jheckjr/recipe-box2
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { createStore, compose, StoreEnhancer } from 'redux'; import { AppStore } from './app-store'; import { RecipeState, RecipeReducer } from './reducers/recipe-reducer'; import { AppComponent } from './app.component'; import { RecipeListComponent } from './recipe-list/recipe-list.component'; import { RecipeItemComponent } from './recipe-item/recipe-item.component'; import { RecipeEditComponent } from './recipe-edit/recipe-edit.component'; // Add DevTools Integration let devtools: StoreEnhancer<RecipeState> = window['devToolsExtension'] ? window['devToolsExtension']() : f => f; let store = createStore<RecipeState>(RecipeReducer, compose(devtools)); export function storeFactory() { return store; } @NgModule({ declarations: [ AppComponent, RecipeListComponent, RecipeItemComponent, RecipeEditComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, HttpModule ], providers: [{ provide: AppStore, useFactory: storeFactory }], bootstrap: [AppComponent] }) export class AppModule { }
jheckjr/recipe-box2
src/app/recipe-list/test/test-recipes.ts
<filename>src/app/recipe-list/test/test-recipes.ts import { Recipe } from '../../models'; export let testRecipes: Recipe[] = [ { name: 'Oatmeal', ingredients: [ '1 pkt. oatmeal', '2/3 cup milk' ] }, { name: 'Rice', ingredients: [ '1/3 cup rice', '2/3 cup water' ] }, { name: 'Chili Pasta Skillet', ingredients: [ '1 lb. lean ground beef', '3/4 cup chopped onion', '15 oz. can black beans', '14.5 oz. can diced tomatoes', '8 oz. can tomato sauce', '1/2 cup dried elbow macaroni', '4 oz. can diced green chile peppers', '2-3 tsp. chili powder', '1/2 tsp. garlic salt', '1/2 cup shredded cheddar cheese' ] } ];
jheckjr/recipe-box2
src/app/local-storage-helper/local-storage-helper.ts
<gh_stars>0 import { Recipe } from '../models'; import { RecipeEntities } from '../reducers/recipe-reducer'; export const storeRecipe = (recipe: Recipe) => { localStorage.setItem(recipe.name, JSON.stringify(recipe)); }; export const deleteStoredRecipe = (recipeName: string) => { localStorage.removeItem(recipeName); }; export const getAllStoredRecipes = (): RecipeEntities => { let recipes: RecipeEntities = {}; for (let i = 0; i < localStorage.length; i++) { let recipeName = localStorage.key(i); let recipe: Recipe = JSON.parse(localStorage.getItem(recipeName)); recipes = Object.assign(recipes, { [recipeName]: recipe }); } return recipes; }; export const getAllStoredRecipeNames = (): string[] => { let recipeNames: string[] = []; for (let i = 0; i < localStorage.length; i++) { recipeNames.push(localStorage.key(i)); } return recipeNames; };
jheckjr/recipe-box2
src/app/models/recipe.model.ts
/* * Recipe represents a single recipe of ingredients */ export interface Recipe { name: string; ingredients: string[]; }
jheckjr/recipe-box2
src/app/actions/index.ts
export * from './user-control'; export * from './recipe-actions';
jheckjr/recipe-box2
src/app/recipe-list/recipe-list.component.ts
<reponame>jheckjr/recipe-box2<gh_stars>0 import { Component, Inject } from '@angular/core'; import { AppStore } from '../app-store'; import { UserControl, addRecipe, deleteRecipe, selectRecipe, editRecipe, updateUserControl } from '../actions'; import { RecipeState, getAllRecipes } from '../reducers/recipe-reducer'; import { RecipeItemComponent } from '../recipe-item/recipe-item.component'; import { RecipeEditComponent } from '../recipe-edit/recipe-edit.component'; import { Recipe, RecipeItemEventType, RecipeItemEvent } from '../models'; @Component({ selector: 'app-recipe-list', templateUrl: './recipe-list.component.html', styleUrls: ['./recipe-list.component.css'] }) export class RecipeListComponent { recipes: Recipe[]; currentRecipe: string; userEditing: boolean; addRecipe: boolean; constructor( @Inject(AppStore) private store) { store.subscribe(() => this.updateState()); this.updateState(); } updateState() { let state = this.store.getState(); this.recipes = getAllRecipes(state); this.currentRecipe = state.currentRecipe; this.userEditing = (state.userControl === UserControl.Edit); this.addRecipe = (state.userControl === UserControl.Add); } handleRecipeEvent(event: RecipeItemEvent) { switch (event.eventType) { case RecipeItemEventType.Edit: this.store.dispatch(updateUserControl(UserControl.Edit)); break; case RecipeItemEventType.Cancel: this.store.dispatch(updateUserControl(UserControl.View)); break; case RecipeItemEventType.Delete: this.store.dispatch(deleteRecipe(event.recipe)); break; case RecipeItemEventType.Save: if (this.userEditing) { this.store.dispatch(editRecipe(event.recipe)); } else if (this.addRecipe) { this.store.dispatch(addRecipe(event.recipe)); } break; default: break; } } // Show/hide a recipe handleRecipeToggle(recipeName: string) { this.store.dispatch(selectRecipe(recipeName)); } // Add button clicked handleAddRecipe() { this.store.dispatch(updateUserControl(UserControl.Add)); } }
jheckjr/recipe-box2
src/app/app.component.spec.ts
/* tslint:disable:no-unused-variable */ import { TestBed, ComponentFixture, async } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; import { createStore } from 'redux'; import { AppStore } from './app-store'; import { RecipeState, RecipeReducer } from './reducers/recipe-reducer'; import { AppComponent } from './app.component'; import { RecipeListComponent } from './recipe-list/recipe-list.component'; import { RecipeItemComponent } from './recipe-item/recipe-item.component'; import { RecipeEditComponent } from './recipe-edit/recipe-edit.component'; describe('AppComponent', () => { let fixture: ComponentFixture<AppComponent>; let app: AppComponent; let store = createStore<RecipeState>(RecipeReducer); function storeFactory() { return store; } beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent, RecipeListComponent, RecipeItemComponent, RecipeEditComponent ], imports: [ReactiveFormsModule], providers: [FormBuilder, { provide: AppStore, useFactory: storeFactory } ] }); TestBed.compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AppComponent); app = fixture.componentInstance; fixture.detectChanges(); }); it(`should create the app with title 'RecipeBox'`, () => { expect(app).toBeDefined(); expect(app.title).toEqual('Recipe Box'); expect(app.subtitle).toEqual('A place to store all your favorite recipes!'); }); it('should render title in a h1 tag', () => { let titleEl = fixture.debugElement.query(By.css('h1')).nativeElement; let subtitleEl = fixture.debugElement.query(By.css('div.box-subheader')).nativeElement; expect(titleEl.textContent).toContain('Recipe Box'); expect(subtitleEl.textContent).toContain('A place to store all your favorite recipes!'); }); });
jheckjr/recipe-box2
src/app/models/recipe-item-event.model.ts
import { Recipe } from './recipe.model'; export interface RecipeItemEvent { eventType: RecipeItemEventType; recipe: Recipe; } export enum RecipeItemEventType { Delete, Edit, Save, Cancel }
jeffersonsouza/stencil-user-profile
src/components/card/card.tsx
import { Component, h, Prop } from '@stencil/core'; @Component({ tag: 'profile-card', styleUrl: 'card.css', shadow: true }) export class Card { @Prop() name: string; @Prop() avatar: string; @Prop() description: string; render() { // Thanks to https://codepen.io/colinkeany/pen/XJOvXz return ( <div class="container"> <div class="avatar"> <img src={this.avatar} height="150" width="150" /> </div> <h2>{this.name}</h2> <p>{this.description}</p> </div> ); } }
basu-dev/ngx-lightbox
src/lightbox.service.ts
import { ApplicationRef, ComponentFactoryResolver, ComponentRef, Inject, Injectable, Injector } from '@angular/core'; import { LightboxComponent } from './lightbox.component'; import { LightboxConfig } from './lightbox-config.service'; import { LightboxEvent, LIGHTBOX_EVENT, IAlbum } from './lightbox-event.service'; import { LightboxOverlayComponent } from './lightbox-overlay.component'; import { DOCUMENT } from '@angular/common'; @Injectable() export class Lightbox { constructor( private _componentFactoryResolver: ComponentFactoryResolver, private _injector: Injector, private _applicationRef: ApplicationRef, private _lightboxConfig: LightboxConfig, private _lightboxEvent: LightboxEvent, @Inject(DOCUMENT) private _documentRef ) { } open(album: Array<IAlbum>, curIndex = 0, options = {}): void { const overlayComponentRef = this._createComponent(LightboxOverlayComponent); const componentRef = this._createComponent(LightboxComponent); const newOptions: Partial<LightboxConfig> = {}; // broadcast open event this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.OPEN }); Object.assign(newOptions, this._lightboxConfig, options); // attach input to lightbox componentRef.instance.album = album; componentRef.instance.currentImageIndex = curIndex; componentRef.instance.options = newOptions; componentRef.instance.cmpRef = componentRef; // attach input to overlay overlayComponentRef.instance.options = newOptions; overlayComponentRef.instance.cmpRef = overlayComponentRef; // FIXME: not sure why last event is broadcasted (which is CLOSED) and make // lightbox can not be opened the second time. // Need to timeout so that the OPEN event is set before component is initialized setTimeout(() => { this._applicationRef.attachView(overlayComponentRef.hostView); this._applicationRef.attachView(componentRef.hostView); overlayComponentRef.onDestroy(() => { this._applicationRef.detachView(overlayComponentRef.hostView); }); componentRef.onDestroy(() => { this._applicationRef.detachView(componentRef.hostView); }); const containerElement = newOptions.containerElementResolver(this._documentRef); containerElement.appendChild(overlayComponentRef.location.nativeElement); containerElement.appendChild(componentRef.location.nativeElement); }); } close(): void { if (this._lightboxEvent) { this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.CLOSE }); } } _createComponent(ComponentClass: any): ComponentRef<any> { const factory = this._componentFactoryResolver.resolveComponentFactory(ComponentClass); const component = factory.create(this._injector); return component; } }
basu-dev/ngx-lightbox
src/lightbox.component.ts
import { FileSaverService } from 'ngx-filesaver'; import { DOCUMENT } from '@angular/common'; import { AfterViewInit, Component, ElementRef, Inject, Input, OnDestroy, OnInit, Renderer2, SecurityContext, ViewChild, } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; import { IAlbum, IEvent, LIGHTBOX_EVENT, LightboxEvent, LightboxWindowRef, } from './lightbox-event.service'; @Component({ template: ` <div class="lb-outerContainer transition" #outerContainer id="outerContainer"> <div class="lb-container" #container id="container"> <img class="lb-image" id="image" [src]="album[currentImageIndex].src" class="lb-image animation fadeIn" [hidden]="ui.showReloader" #image> <div class="lb-nav" [hidden]="!ui.showArrowNav" #navArrow> <a class="lb-prev" [hidden]="!ui.showLeftArrow" (click)="prevImage()" #leftArrow></a> <a class="lb-next" [hidden]="!ui.showRightArrow" (click)="nextImage()" #rightArrow></a> </div> <div class="lb-loader" [hidden]="!ui.showReloader" (click)="close($event)"> <a class="lb-cancel"></a> </div> </div> </div> <div class="lb-dataContainer" [hidden]="ui.showReloader" #dataContainer> <div class="lb-data"> <div class="lb-details"> <span class="lb-caption animation fadeIn" [hidden]="!ui.showCaption" [innerHtml]="album[currentImageIndex].caption" #caption> </span> <span class="lb-number animation fadeIn" [hidden]="!ui.showPageNumber" #number>{{ content.pageNumber }}</span> </div> <div class="lb-controlContainer"> <div class="lb-closeContainer"> <a class="lb-close" (click)="close($event)"></a> </div> <div class="lb-downloadContainer" [hidden]="!ui.showDownloadButton"> <a class="lb-download" (click)="download($event)"></a> </div> <div class="lb-turnContainer" [hidden]="!ui.showRotateButton"> <a class="lb-turnLeft" (click)="control($event)"></a> <a class="lb-turnRight" (click)="control($event)"></a> </div> <div class="lb-zoomContainer" [hidden]="!ui.showZoomButton"> <a class="lb-zoomOut" (click)="control($event)"></a> <a class="lb-zoomIn" (click)="control($event)"></a> </div> </div> </div> </div>`, selector: '[lb-content]', host: { '(click)': 'close($event)', '[class]': 'ui.classList' } }) export class LightboxComponent implements OnInit, AfterViewInit, OnDestroy, OnInit { @Input() album: Array<IAlbum>; @Input() currentImageIndex: number; @Input() options: any; @Input() cmpRef: any; @ViewChild('outerContainer', { static: false }) _outerContainerElem: ElementRef; @ViewChild('container', { static: false }) _containerElem: ElementRef; @ViewChild('leftArrow', { static: false }) _leftArrowElem: ElementRef; @ViewChild('rightArrow', { static: false }) _rightArrowElem: ElementRef; @ViewChild('navArrow', { static: false }) _navArrowElem: ElementRef; @ViewChild('dataContainer', { static: false }) _dataContainerElem: ElementRef; @ViewChild('image', { static: false }) _imageElem: ElementRef; @ViewChild('caption', { static: false }) _captionElem: ElementRef; @ViewChild('number', { static: false }) _numberElem: ElementRef; public content: any; public ui: any; private _cssValue: any; private _event: any; private _windowRef: any; private rotate: number; constructor( private _elemRef: ElementRef, private _rendererRef: Renderer2, private _lightboxEvent: LightboxEvent, public _lightboxElem: ElementRef, private _lightboxWindowRef: LightboxWindowRef, private _fileSaverService: FileSaverService, private _sanitizer: DomSanitizer, @Inject(DOCUMENT) private _documentRef ) { // initialize data this.options = this.options || {}; this.album = this.album || []; this.currentImageIndex = this.currentImageIndex || 0; this._windowRef = this._lightboxWindowRef.nativeWindow; // control the interactive of the directive this.ui = { // control the appear of the reloader // false: image has loaded completely and ready to be shown // true: image is still loading showReloader: true, // control the appear of the nav arrow // the arrowNav is the parent of both left and right arrow // in some cases, the parent shows but the child does not show showLeftArrow: false, showRightArrow: false, showArrowNav: false, // control the appear of the zoom and rotate buttons showZoomButton: false, showRotateButton: false, // control whether to show the // page number or not showPageNumber: false, showCaption: false, // control whether to show the download button or not showDownloadButton: false, classList: 'lightbox animation fadeIn' }; this.content = { pageNumber: '' }; this._event = {}; this._lightboxElem = this._elemRef; this._event.subscription = this._lightboxEvent.lightboxEvent$ .subscribe((event: IEvent) => this._onReceivedEvent(event)); this.rotate = 0; } ngOnInit(): void { this.album.forEach(album => { if (album.caption) { album.caption = this._sanitizer.sanitize(SecurityContext.HTML, album.caption); } }); } public ngAfterViewInit(): void { // need to init css value here, after the view ready // actually these values are always 0 this._cssValue = { containerTopPadding: Math.round(this._getCssStyleValue(this._containerElem, 'padding-top')), containerRightPadding: Math.round(this._getCssStyleValue(this._containerElem, 'padding-right')), containerBottomPadding: Math.round(this._getCssStyleValue(this._containerElem, 'padding-bottom')), containerLeftPadding: Math.round(this._getCssStyleValue(this._containerElem, 'padding-left')), imageBorderWidthTop: Math.round(this._getCssStyleValue(this._imageElem, 'border-top-width')), imageBorderWidthBottom: Math.round(this._getCssStyleValue(this._imageElem, 'border-bottom-width')), imageBorderWidthLeft: Math.round(this._getCssStyleValue(this._imageElem, 'border-left-width')), imageBorderWidthRight: Math.round(this._getCssStyleValue(this._imageElem, 'border-right-width')) }; if (this._validateInputData()) { this._prepareComponent(); this._registerImageLoadingEvent(); } } public ngOnDestroy(): void { if (!this.options.disableKeyboardNav) { // unbind keyboard event this._disableKeyboardNav(); } this._event.subscription.unsubscribe(); } public close($event: any): void { $event.stopPropagation(); if ($event.target.classList.contains('lightbox') || $event.target.classList.contains('lb-loader') || $event.target.classList.contains('lb-close')) { this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.CLOSE, data: null }); } } public download($event: any): void { $event.stopPropagation(); const url = this.album[this.currentImageIndex].src; const parts = url.split('/'); const fileName = parts[parts.length - 1]; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const preloader = new Image(); const _this = this preloader.onload = function () { // @ts-ignore canvas.width = this.naturalWidth; // @ts-ignore canvas.height = this.naturalHeight; // @ts-ignore ctx.drawImage(this, 0, 0); canvas.toBlob(function (blob) { _this._fileSaverService.save(blob, fileName) }, 'image/jpeg', 0.75); }; preloader.crossOrigin = ''; preloader.src = this._sanitizer.sanitize(SecurityContext.URL, url); } public control($event: any): void { $event.stopPropagation(); let height: number; let width: number; if ($event.target.classList.contains('lb-turnLeft')) { this.rotate = this.rotate - 90; this._rotateContainer(); this._calcTransformPoint(); this._documentRef.getElementById('image').style.transform = `rotate(${this.rotate}deg)`; this._documentRef.getElementById('image').style.webkitTransform = `rotate(${this.rotate}deg)`; this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.ROTATE_LEFT, data: null }); } else if ($event.target.classList.contains('lb-turnRight')) { this.rotate = this.rotate + 90; this._rotateContainer(); this._calcTransformPoint(); this._documentRef.getElementById('image').style.transform = `rotate(${this.rotate}deg)`; this._documentRef.getElementById('image').style.webkitTransform = `rotate(${this.rotate}deg)`; this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.ROTATE_RIGHT, data: null }); } else if ($event.target.classList.contains('lb-zoomOut')) { height = parseInt(this._documentRef.getElementById('outerContainer').style.height, 10) / 1.5; width = parseInt(this._documentRef.getElementById('outerContainer').style.width, 10) / 1.5; this._documentRef.getElementById('outerContainer').style.height = height + 'px'; this._documentRef.getElementById('outerContainer').style.width = width + 'px'; height = parseInt(this._documentRef.getElementById('image').style.height, 10) / 1.5; width = parseInt(this._documentRef.getElementById('image').style.width, 10) / 1.5; this._documentRef.getElementById('image').style.height = height + 'px'; this._documentRef.getElementById('image').style.width = width + 'px'; this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.ZOOM_OUT, data: null }); } else if ($event.target.classList.contains('lb-zoomIn')) { height = parseInt(this._documentRef.getElementById('outerContainer').style.height, 10) * 1.5; width = parseInt(this._documentRef.getElementById('outerContainer').style.width, 10) * 1.5; this._documentRef.getElementById('outerContainer').style.height = height + 'px'; this._documentRef.getElementById('outerContainer').style.width = width + 'px'; height = parseInt(this._documentRef.getElementById('image').style.height, 10) * 1.5; width = parseInt(this._documentRef.getElementById('image').style.width, 10) * 1.5; this._documentRef.getElementById('image').style.height = height + 'px'; this._documentRef.getElementById('image').style.width = width + 'px'; this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.ZOOM_IN, data: null }); } } private _rotateContainer(): void { let temp = this.rotate; if (temp < 0) { temp *= -1; } if (temp / 90 % 4 === 1 || temp / 90 % 4 === 3) { this._documentRef.getElementById('outerContainer').style.height = this._documentRef.getElementById('image').style.width; this._documentRef.getElementById('outerContainer').style.width = this._documentRef.getElementById('image').style.height; this._documentRef.getElementById('container').style.height = this._documentRef.getElementById('image').style.width; this._documentRef.getElementById('container').style.width = this._documentRef.getElementById('image').style.height; } else { this._documentRef.getElementById('outerContainer').style.height = this._documentRef.getElementById('image').style.height; this._documentRef.getElementById('outerContainer').style.width = this._documentRef.getElementById('image').style.width; this._documentRef.getElementById('container').style.height = this._documentRef.getElementById('image').style.width; this._documentRef.getElementById('container').style.width = this._documentRef.getElementById('image').style.height; } } private _resetImage(): void { this.rotate = 0; this._documentRef.getElementById('image').style.transform = `rotate(${this.rotate}deg)`; this._documentRef.getElementById('image').style.webkitTransform = `rotate(${this.rotate}deg)`; } private _calcTransformPoint(): void { let height = parseInt(this._documentRef.getElementById('image').style.height, 10); let width = parseInt(this._documentRef.getElementById('image').style.width, 10); let temp = this.rotate % 360; if (temp < 0) { temp = 360 + temp; } if (temp === 90) { this._documentRef.getElementById('image').style.transformOrigin = (height / 2) + 'px ' + (height / 2) + 'px'; } else if (temp === 180) { this._documentRef.getElementById('image').style.transformOrigin = (width / 2) + 'px ' + (height / 2) + 'px'; } else if (temp === 270) { this._documentRef.getElementById('image').style.transformOrigin = (width / 2) + 'px ' + (width / 2) + 'px'; } } public nextImage(): void { if (this.album.length === 1) { return; } else if (this.currentImageIndex === this.album.length - 1) { this._changeImage(0); } else { this._changeImage(this.currentImageIndex + 1); } } public prevImage(): void { if (this.album.length === 1) { return; } else if (this.currentImageIndex === 0 && this.album.length > 1) { this._changeImage(this.album.length - 1); } else { this._changeImage(this.currentImageIndex - 1); } } private _validateInputData(): boolean { if (this.album && this.album instanceof Array && this.album.length > 0) { for (let i = 0; i < this.album.length; i++) { // check whether each _nside // album has src data or not if (this.album[i].src) { continue; } throw new Error('One of the album data does not have source data'); } } else { throw new Error('No album data or album data is not correct in type'); } // to prevent data understand as string // convert it to number if (isNaN(this.currentImageIndex)) { throw new Error('Current image index is not a number'); } else { this.currentImageIndex = Number(this.currentImageIndex); } return true; } private _registerImageLoadingEvent(): void { const preloader = new Image(); preloader.onload = () => { this._onLoadImageSuccess(); } const src: any = this.album[this.currentImageIndex].src; preloader.src = this._sanitizer.sanitize(SecurityContext.URL, src); } /** * Fire when the image is loaded */ private _onLoadImageSuccess(): void { if (!this.options.disableKeyboardNav) { // unbind keyboard event during transition this._disableKeyboardNav(); } let imageHeight; let imageWidth; let maxImageHeight; let maxImageWidth; let windowHeight; let windowWidth; let naturalImageWidth; let naturalImageHeight; // set default width and height of image to be its natural imageWidth = naturalImageWidth = this._imageElem.nativeElement.naturalWidth; imageHeight = naturalImageHeight = this._imageElem.nativeElement.naturalHeight; if (this.options.fitImageInViewPort) { windowWidth = this._windowRef.innerWidth; windowHeight = this._windowRef.innerHeight; maxImageWidth = windowWidth - this._cssValue.containerLeftPadding - this._cssValue.containerRightPadding - this._cssValue.imageBorderWidthLeft - this._cssValue.imageBorderWidthRight - 20; maxImageHeight = windowHeight - this._cssValue.containerTopPadding - this._cssValue.containerTopPadding - this._cssValue.imageBorderWidthTop - this._cssValue.imageBorderWidthBottom - 120; if (naturalImageWidth > maxImageWidth || naturalImageHeight > maxImageHeight) { if ((naturalImageWidth / maxImageWidth) > (naturalImageHeight / maxImageHeight)) { imageWidth = maxImageWidth; imageHeight = Math.round(naturalImageHeight / (naturalImageWidth / imageWidth)); } else { imageHeight = maxImageHeight; imageWidth = Math.round(naturalImageWidth / (naturalImageHeight / imageHeight)); } } this._rendererRef.setStyle(this._imageElem.nativeElement, 'width', `${imageWidth}px`); this._rendererRef.setStyle(this._imageElem.nativeElement, 'height', `${imageHeight}px`); } this._sizeContainer(imageWidth, imageHeight); if (this.options.centerVertically) { this._centerVertically(imageWidth, imageHeight); } } private _centerVertically(imageWidth: number, imageHeight: number): void { const scrollOffset = this._documentRef.documentElement.scrollTop; const windowHeight = this._windowRef.innerHeight; const viewOffset = windowHeight / 2 - imageHeight / 2; const topDistance = scrollOffset + viewOffset; this._rendererRef.setStyle(this._lightboxElem.nativeElement, 'top', `${topDistance}px`); } private _sizeContainer(imageWidth: number, imageHeight: number): void { const oldWidth = this._outerContainerElem.nativeElement.offsetWidth; const oldHeight = this._outerContainerElem.nativeElement.offsetHeight; const newWidth = imageWidth + this._cssValue.containerRightPadding + this._cssValue.containerLeftPadding + this._cssValue.imageBorderWidthLeft + this._cssValue.imageBorderWidthRight; const newHeight = imageHeight + this._cssValue.containerTopPadding + this._cssValue.containerBottomPadding + this._cssValue.imageBorderWidthTop + this._cssValue.imageBorderWidthBottom; // make sure that distances are large enough for transitionend event to be fired, at least 5px. if (Math.abs(oldWidth - newWidth) + Math.abs(oldHeight - newHeight) > 5) { this._rendererRef.setStyle(this._outerContainerElem.nativeElement, 'width', `${newWidth}px`); this._rendererRef.setStyle(this._outerContainerElem.nativeElement, 'height', `${newHeight}px`); // bind resize event to outer container // use enableTransition to prevent infinite loader if (this.options.enableTransition) { this._event.transitions = []; ['transitionend', 'webkitTransitionEnd', 'oTransitionEnd', 'MSTransitionEnd'].forEach(eventName => { this._event.transitions.push( this._rendererRef.listen(this._outerContainerElem.nativeElement, eventName, (event: any) => { if (event.target === event.currentTarget) { this._postResize(newWidth, newHeight); } }) ); }); } else { this._postResize(newWidth, newHeight); } } else { this._postResize(newWidth, newHeight); } } private _postResize(newWidth: number, newHeight: number): void { // unbind resize event if (Array.isArray(this._event.transitions)) { this._event.transitions.forEach((eventHandler: any) => { eventHandler(); }); this._event.transitions = []; } this._rendererRef.setStyle(this._dataContainerElem.nativeElement, 'width', `${newWidth}px`); this._showImage(); } private _showImage(): void { this.ui.showReloader = false; this._updateNav(); this._updateDetails(); if (!this.options.disableKeyboardNav) { this._enableKeyboardNav(); } } private _prepareComponent(): void { // add css3 animation this._addCssAnimation(); // position the image according to user's option this._positionLightBox(); // update controls visibility on next view generation setTimeout(() => { this.ui.showZoomButton = this.options.showZoom; this.ui.showRotateButton = this.options.showRotate; this.ui.showDownloadButton = this.options.showDownloadButton; }, 0); } private _positionLightBox(): void { // @see https://stackoverflow.com/questions/3464876/javascript-get-window-x-y-position-for-scroll const top = (this._windowRef.pageYOffset || this._documentRef.documentElement.scrollTop) + this.options.positionFromTop; const left = this._windowRef.pageXOffset || this._documentRef.documentElement.scrollLeft; if (!this.options.centerVertically) { this._rendererRef.setStyle(this._lightboxElem.nativeElement, 'top', `${top}px`); } this._rendererRef.setStyle(this._lightboxElem.nativeElement, 'left', `${left}px`); this._rendererRef.setStyle(this._lightboxElem.nativeElement, 'display', 'block'); // disable scrolling of the page while open if (this.options.disableScrolling) { this._rendererRef.addClass(this._documentRef.documentElement, 'lb-disable-scrolling'); } } /** * addCssAnimation add css3 classes for animate lightbox */ private _addCssAnimation(): void { const resizeDuration = this.options.resizeDuration; const fadeDuration = this.options.fadeDuration; this._rendererRef.setStyle(this._lightboxElem.nativeElement, '-webkit-animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._lightboxElem.nativeElement, 'animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._outerContainerElem.nativeElement, '-webkit-transition-duration', `${resizeDuration}s`); this._rendererRef.setStyle(this._outerContainerElem.nativeElement, 'transition-duration', `${resizeDuration}s`); this._rendererRef.setStyle(this._dataContainerElem.nativeElement, '-webkit-animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._dataContainerElem.nativeElement, 'animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._imageElem.nativeElement, '-webkit-animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._imageElem.nativeElement, 'animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._captionElem.nativeElement, '-webkit-animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._captionElem.nativeElement, 'animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._numberElem.nativeElement, '-webkit-animation-duration', `${fadeDuration}s`); this._rendererRef.setStyle(this._numberElem.nativeElement, 'animation-duration', `${fadeDuration}s`); } private _end(): void { this.ui.classList = 'lightbox animation fadeOut'; if (this.options.disableScrolling) { this._rendererRef.removeClass(this._documentRef.documentElement, 'lb-disable-scrolling'); } setTimeout(() => { this.cmpRef.destroy(); }, this.options.fadeDuration * 1000); } private _updateDetails(): void { // update the caption if (typeof this.album[this.currentImageIndex].caption !== 'undefined' && this.album[this.currentImageIndex].caption !== '') { this.ui.showCaption = true; } // update the page number if user choose to do so // does not perform numbering the page if the // array length in album <= 1 if (this.album.length > 1 && this.options.showImageNumberLabel) { this.ui.showPageNumber = true; this.content.pageNumber = this._albumLabel(); } } private _albumLabel(): string { // due to {this.currentImageIndex} is set from 0 to {this.album.length} - 1 return this.options.albumLabel.replace(/%1/g, Number(this.currentImageIndex + 1)).replace(/%2/g, this.album.length); } private _changeImage(newIndex: number): void { this._resetImage(); this.currentImageIndex = newIndex; this._hideImage(); this._registerImageLoadingEvent(); this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.CHANGE_PAGE, data: newIndex }); } private _hideImage(): void { this.ui.showReloader = true; this.ui.showArrowNav = false; this.ui.showLeftArrow = false; this.ui.showRightArrow = false; this.ui.showPageNumber = false; this.ui.showCaption = false; } private _updateNav(): void { let alwaysShowNav = false; // check to see the browser support touch event try { this._documentRef.createEvent('TouchEvent'); alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false; } catch (e) { // noop } // initially show the arrow nav // which is the parent of both left and right nav this._showArrowNav(); if (this.album.length > 1) { if (this.options.wrapAround) { if (alwaysShowNav) { // alternatives this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1'); this._rendererRef.setStyle(this._leftArrowElem.nativeElement, 'opacity', '1'); this._rendererRef.setStyle(this._rightArrowElem.nativeElement, 'opacity', '1'); } // alternatives this.$lightbox.find('.lb-prev, .lb-next').show(); this._showLeftArrowNav(); this._showRightArrowNav(); } else { if (this.currentImageIndex > 0) { // alternatives this.$lightbox.find('.lb-prev').show(); this._showLeftArrowNav(); if (alwaysShowNav) { // alternatives this.$lightbox.find('.lb-prev').css('opacity', '1'); this._rendererRef.setStyle(this._leftArrowElem.nativeElement, 'opacity', '1'); } } if (this.currentImageIndex < this.album.length - 1) { // alternatives this.$lightbox.find('.lb-next').show(); this._showRightArrowNav(); if (alwaysShowNav) { // alternatives this.$lightbox.find('.lb-next').css('opacity', '1'); this._rendererRef.setStyle(this._rightArrowElem.nativeElement, 'opacity', '1'); } } } } } private _showLeftArrowNav(): void { this.ui.showLeftArrow = true; } private _showRightArrowNav(): void { this.ui.showRightArrow = true; } private _showArrowNav(): void { this.ui.showArrowNav = (this.album.length !== 1); } private _enableKeyboardNav(): void { this._event.keyup = this._rendererRef.listen('document', 'keyup', (event: any) => { this._keyboardAction(event); }); } private _disableKeyboardNav(): void { if (this._event.keyup) { this._event.keyup(); } } private _keyboardAction($event: any): void { const KEYCODE_ESC = 27; const KEYCODE_LEFTARROW = 37; const KEYCODE_RIGHTARROW = 39; const keycode = $event.keyCode; const key = String.fromCharCode(keycode).toLowerCase(); if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) { this._lightboxEvent.broadcastLightboxEvent({ id: LIGHTBOX_EVENT.CLOSE, data: null }); } else if (key === 'p' || keycode === KEYCODE_LEFTARROW) { if (this.currentImageIndex !== 0) { this._changeImage(this.currentImageIndex - 1); } else if (this.options.wrapAround && this.album.length > 1) { this._changeImage(this.album.length - 1); } } else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) { if (this.currentImageIndex !== this.album.length - 1) { this._changeImage(this.currentImageIndex + 1); } else if (this.options.wrapAround && this.album.length > 1) { this._changeImage(0); } } } private _getCssStyleValue(elem: any, propertyName: string): number { return parseFloat(this._windowRef .getComputedStyle(elem.nativeElement, null) .getPropertyValue(propertyName)); } private _onReceivedEvent(event: IEvent): void { switch (event.id) { case LIGHTBOX_EVENT.CLOSE: this._end(); break; default: break; } } }
harmanpa/configurator-example
client/src/app/three/renderer/selection-manager.ts
import {AbstractObject3D} from '../objects/abstract-object-3d'; import * as THREE from 'three'; import {Subject} from 'rxjs'; export class SelectionManager { private scene: AbstractObject3D<THREE.Object3D>; private hovered: Map<THREE.Object3D, AbstractObject3D<THREE.Object3D>>; private selected: Map<THREE.Object3D, AbstractObject3D<THREE.Object3D>>; private selectionChange: Subject<AbstractObject3D<THREE.Object3D>[]>; private hoverChange: Subject<AbstractObject3D<THREE.Object3D>[]>; constructor(scene: AbstractObject3D<THREE.Object3D>, selectionChange: Subject<AbstractObject3D<THREE.Object3D> []>, hoverChange: Subject<AbstractObject3D<THREE.Object3D>[]>) { this.scene = scene; this.hovered = new Map<THREE.Object3D, AbstractObject3D<THREE.Object3D>>(); this.selected = new Map<THREE.Object3D, AbstractObject3D<THREE.Object3D>>(); this.hoverChange = hoverChange; this.selectionChange = selectionChange; } public setHovered(objects: THREE.Object3D[]): void { // Added const added = objects.filter((obj) => !this.hovered.has(obj)); // Removed const removed = Array.from(this.hovered.keys()).filter((obj) => objects.indexOf(obj) === -1); // Apply removed removed.forEach((obj) => { const component = this.hovered.get(obj); if (component) { component.onMouseOut(); } this.hovered.delete(obj); }); // Apply added added.forEach((obj) => { const component = this.scene.find(obj); if (component) { component.onMouseOver(); } this.hovered.set(obj, component); }); // Fire event if (added.length > 0 || removed.length > 0) { this.hoverChange.next(this.getHovered()); } } public setSelected(objects: THREE.Object3D[]): void { // Added const added = objects.filter((obj) => !this.selected.has(obj)); // Remained const remained = objects.filter((obj) => this.selected.has(obj)); // Removed const removed = Array.from(this.selected.keys()).filter((obj) => objects.indexOf(obj) === -1); // Apply removed removed.forEach((obj) => { const component = this.selected.get(obj); if (component) { component.onDeselect(); } this.selected.delete(obj); }); // Apply remained remained.forEach((obj) => { const component = this.selected.get(obj); if (component) { component.onClick(); } }); // Apply added added.forEach((obj) => { const component = this.scene.find(obj); if (component) { component.onClick(); component.onSelect(); } this.selected.set(obj, component); }); // Fire event if (added.length > 0 || removed.length > 0) { this.selectionChange.next(this.getSelected()); } } public toggleSelected(objects: THREE.Object3D[]): void { // Added const added = objects.filter((obj) => !this.selected.has(obj)); // Removed const removed = objects.filter((obj) => this.selected.has(obj)); // Apply removed removed.forEach((obj) => { const component = this.selected.get(obj); if (component) { component.onClick(); component.onDeselect(); } this.hovered.delete(obj); } ); // Apply added added.forEach((obj) => { const component = this.scene.find(obj); if (component) { component.onClick(); component.onSelect(); } this.selected.set(obj, component); }); // Fire event if (added.length > 0 || removed.length > 0) { this.selectionChange.next(this.getSelected()); } } public getHovered(): AbstractObject3D<THREE.Object3D>[] { return Array.from(this.hovered.values()).filter((obj) => obj !== null); } public getSelected(): AbstractObject3D<THREE.Object3D>[] { return Array.from(this.selected.values()).filter((obj) => obj !== null); } }
harmanpa/configurator-example
client/src/app/three/objects/abstract-object-3d.ts
/* * The MIT License * * Copyright (c) 2017 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import { AfterContentInit, AfterViewInit, ViewChildren, ContentChildren, EventEmitter, Input, OnChanges, Output, QueryList, SimpleChanges, OnDestroy } from '@angular/core'; import * as THREE from 'three'; import {WebGLRendererComponent} from '../renderer/webgl-renderer.component'; import {AbstractMaterial} from './abstract-material'; export abstract class AbstractObject3D<T extends THREE.Object3D> implements AfterViewInit, OnChanges, AfterContentInit, OnDestroy { renderer: WebGLRendererComponent; @ViewChildren(AbstractObject3D) viewNodes: QueryList<AbstractObject3D<THREE.Object3D>>; @ContentChildren(AbstractObject3D, {descendants: false}) contentNodes: QueryList<AbstractObject3D<THREE.Object3D>>; @ContentChildren(AbstractMaterial, {descendants: false}) materials: QueryList<AbstractMaterial>; /** * Rotation in Euler angles (radians) with order X, Y, Z. */ @Input() rotateX: number; /** * Rotation in Euler angles (radians) with order X, Y, Z. */ @Input() rotateY: number; /** * Rotation in Euler angles (radians) with order X, Y, Z. */ @Input() rotateZ: number; @Input() translateX: number; @Input() translateY: number; @Input() translateZ: number; @Input() matrix: number[]; @Input() transposeMatrix = true; @Output() mouseOver: EventEmitter<boolean> = new EventEmitter<boolean>(); @Output() mouseOut: EventEmitter<boolean> = new EventEmitter<boolean>(); @Output() hover: EventEmitter<boolean> = new EventEmitter<boolean>(); @Output() click: EventEmitter<boolean> = new EventEmitter<boolean>(); @Output() select: EventEmitter<boolean> = new EventEmitter<boolean>(); childNodes = new Set<AbstractObject3D<THREE.Object3D>>(); childNodesChange = new EventEmitter<Set<AbstractObject3D<THREE.Object3D>>>(); private object: T; private selected: boolean; protected rerender() { } public ngOnChanges(changes: SimpleChanges) { if (!this.object) { return; } let mustRerender = false; if (['rotateX', 'rotateY', 'rotateZ'].some(propName => propName in changes)) { this.applyRotation(); mustRerender = true; } if (['translateX', 'translateY', 'translateZ'].some(propName => propName in changes)) { this.applyTranslation(); mustRerender = true; } if (['matrix'].some(propName => propName in changes)) { this.applyMatrix(); mustRerender = true; } if (mustRerender) { this.rerender(); } } public updateChildNodes() { this.childNodes.clear(); if (this.viewNodes != null) { this.viewNodes.filter(i => i !== this).forEach(child => this.childNodes.add(child)); } if (this.contentNodes != null) { this.contentNodes.filter(i => i !== this).forEach(child => this.childNodes.add(child)); } this.childNodesChange.emit(this.childNodes); } public setRendererComponent(renderer: WebGLRendererComponent) { this.renderer = renderer; this.childNodes.forEach(child => child.setRendererComponent(renderer)); this.childNodesChange.subscribe((childNodes) => childNodes.forEach(child => child.setRendererComponent(renderer))); this.afterInit(); } public getRendererComponent(): WebGLRendererComponent { return this.renderer; } public ngAfterContentInit(): void { this.updateChildNodes(); } public ngAfterViewInit(): void { this.object = this.newObject3DInstance(); this.applyTranslation(); this.applyRotation(); this.applyMatrix(); this.updateChildNodes(); this.childNodes.forEach(child => this.addChild(child.getObject())); this.childNodesChange.subscribe((childNodes) => { this.object.children.forEach((obj) => this.object.remove(obj)); childNodes.forEach(child => this.addChild(child.getObject())); }); if (this.viewNodes) { this.viewNodes.changes.subscribe((newViewNodes) => { console.log('View nodes change'); console.log(newViewNodes); newViewNodes.forEach((viewNode) => { if (this.object.children.indexOf(viewNode.getObject()) < 0) { viewNode.setRendererComponent(this.renderer); this.object.add(viewNode.getObject()); console.log('Element added'); console.log(viewNode); } }); this.object.children.forEach((object) => { if (newViewNodes.filter((viewNode) => viewNode.getObject() === object).length === 0) { console.log('Element removed'); } }); }); } } /** * * @param object */ public find(object: THREE.Object3D): AbstractObject3D<THREE.Object3D> { if (this.getObject() === object) { return this; } let childResult = null; this.childNodes.forEach((child) => { if (!childResult) { childResult = child.find(object); } }); if (childResult) { return childResult; } // It is not owned by a child component, check if it is child geometry if (this.getObject().getObjectById(object.id)) { return this; } return null; } public findByPath(path: string[]): AbstractObject3D<THREE.Object3D> { if (path && path.length > 0) { if (this.id() && this.id().length > 0) { if (this.id() === path[0]) { if (path.length > 1) { const subPath = path.slice(1); let childResult = null; this.childNodes.forEach((child) => { if (!childResult) { childResult = child.findByPath(subPath); } }); if (childResult) { return childResult; } } else { return this; } } } else { // This applies to Scene or Assembly components, where the components with an id are below let childResult = null; this.childNodes.forEach((child) => { if (!childResult) { childResult = child.findByPath(path); } }); if (childResult) { return childResult; } } } return null; } protected applyMatrix(): void { if (!this.matrix) { return; } const m = new THREE.Matrix4(); switch (this.matrix.length) { case 9: m.set( this.matrix[0], this.matrix[1], this.matrix[2], 0, this.matrix[3], this.matrix[4], this.matrix[5], 0, this.matrix[6], this.matrix[7], this.matrix[8], 0, 0, 0, 0, 1); this.object.matrixAutoUpdate = false; this.object.matrix.copy(this.transposeMatrix ? m.transpose() : m); return; case 16: m.set( this.matrix[0], this.matrix[1], this.matrix[2], this.matrix[3], this.matrix[4], this.matrix[5], this.matrix[6], this.matrix[7], this.matrix[8], this.matrix[9], this.matrix[10], this.matrix[11], this.matrix[12], this.matrix[13], this.matrix[14], this.matrix[15]); this.object.matrixAutoUpdate = false; this.object.matrix.copy(this.transposeMatrix ? m.transpose() : m); return; default: console.log('Wrong matrix length'); } } private applyRotation(): void { this.object.rotation.set( this.rotateX || 0, this.rotateY || 0, this.rotateZ || 0, 'XYZ' ); } private applyTranslation(): void { this.object.position.set( this.translateX || 0, this.translateY || 0, this.translateZ || 0 ); } protected addChild(object: THREE.Object3D): void { this.object.add(object); } protected removeChild(object: THREE.Object3D): void { this.object.remove(object); } public getObject(): T { return this.object; } protected abstract newObject3DInstance(): T; protected abstract afterInit(): void; protected id(): string { return ''; } public onProgress(message: string, progress: number) { console.log(message + progress + this.renderer); if (this.renderer) { this.renderer.onProgress(this.id(), message, progress); } } public onMouseOver(): void { this.mouseOver.emit(); this.hover.emit(true); } public onMouseOut(): void { this.mouseOut.emit(); this.hover.emit(false); } public onClick(): void { this.click.emit(); } public onSelect(): void { this.select.emit(true); } public onDeselect(): void { this.select.emit(false); } ngOnDestroy(): void { this.object.children.forEach((obj) => this.object.remove(obj)); } }
harmanpa/configurator-example
client/src/app/three/transformers/transformer.ts
import * as THREE from 'three'; export abstract class Transformer { prepare(scene: THREE.Scene): boolean { return true; } }
harmanpa/configurator-example
client/src/app/three-tools/camera-controls/camera-controls.component.ts
<reponame>harmanpa/configurator-example<gh_stars>0 /* * The MIT License * * Copyright (c) 2019 Onshape Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import {Component, Input, OnChanges, OnDestroy, forwardRef, SimpleChanges} from '@angular/core'; import {AbstractTool} from '../abstract-tool'; import CameraControls from 'camera-controls'; import * as THREE from 'three'; @Component({ selector: 'app-camera-controls', templateUrl: './camera-controls.component.html', styleUrls: ['./camera-controls.component.scss'], providers: [{provide: AbstractTool, useExisting: forwardRef(() => CameraControlsComponent)}] }) export class CameraControlsComponent extends AbstractTool implements OnChanges, OnDestroy { @Input() zoomToFit = true; @Input() zoomToFitInitial = false; @Input() button = true; private controls: CameraControls; constructor() { super('Camera Controls', 'navigation', true, true); } ngOnChanges(changes: SimpleChanges) { // If the THREE.js OrbitControls are not set up yet, we do not need to update // anything as they will pick the new values from the @Input properties automatically // upon creation. if (!this.controls) { return; } if (changes['listeningControlElement']) { // The DOM element the OrbitControls listen on cannot be changed once an // OrbitControls object is created. We thus need to recreate it. this.controls.dispose(); this.setUpCameraControls(); } } ngOnDestroy() { this.controls.dispose(); } private setUpCameraControls() { console.log('Starting Camera Controls'); CameraControls.install({THREE: THREE}); this.controls = new CameraControls( this.getRendererComponent().getCamera() as THREE.PerspectiveCamera | THREE.OrthographicCamera, this.getRendererComponent().canvas ); this.controls.addEventListener('update', () => { }); // Following line seems to trigger controls to start, unsure why this.controls.addEventListener('control', () => { }); if (this.zoomToFitInitial) { this.doZoomToFit(); } } onStartRendering() { super.onStartRendering(); this.setUpCameraControls(); } onRender(delta: number) { super.onRender(delta); this.controls.update(delta); } public doZoomToFit() { const bbox = new THREE.Box3().setFromObject(this.getRendererComponent().getScene()); if (this.getRendererComponent().getCamera() instanceof THREE.PerspectiveCamera) { this.controls.fitTo(bbox, true); } else { const camera = this.getRendererComponent().getCamera() as THREE.OrthographicCamera; const sphere = new THREE.Sphere(); bbox.getBoundingSphere(sphere); } } }
harmanpa/configurator-example
client/src/app/configurator/services/configurator.service.ts
import {EventEmitter, Injectable, Input} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import { AbstractDocumentElement, Appearance, Configuration, ConfigurationParameter, ConfigurationParameterEnum, ConfigurationParameterQuantity, Configurator, ConfiguredAssembly, ConfiguredPart, EnumOption, ParameterValue, SubAssembly, WVM } from '../../../typescript-generator/configurator'; import {Observable} from 'rxjs'; import {catchError, map} from 'rxjs/operators'; import {STLLoader} from '../../three/js/STLLoader'; import * as THREE from 'three'; import {CacheService} from './cache.service'; import {of} from 'rxjs/internal/observable/of'; @Injectable({ providedIn: 'root' }) export class ConfiguratorService { private loader = new STLLoader(); private nRequested = 0; private nReturned = 0; public progressChange = new EventEmitter<number>(true); public progress: number; constructor(private http: HttpClient, private cache: CacheService) { this.progress = 100; } request() { this.nRequested++; this.progress = this.nRequested === 0 ? 100 : (100 * this.nReturned / this.nRequested); this.progressChange.emit(this.progress); } returned() { this.nReturned++; if (this.nReturned === this.nRequested) { this.nRequested = 0; this.nReturned = 0; } this.progress = this.nRequested === 0 ? 100 : (100 * this.nReturned / this.nRequested); this.progressChange.emit(this.progress); } getConfigurator(documentId: string, wvmType: WVM, wvmId: string, elementId: string): Observable<Configurator> { return this.http.get('/api/configurator' + this.getURLPath(documentId, wvmType, wvmId, elementId)) .pipe(map((result) => result as Configurator)); } getAssembly(configurator: Configurator, configuration: Configuration): Observable<ConfiguredAssembly> { this.request(); // Construct the URL and a key for caching const urlPath = this.getURLPathFor(configurator); const key = 'assemblies' + urlPath + '/c/' + this.getConfigurationString(configuration); // Create an Observable for fetching from the API const fetchAssemblyObservable = new Observable((observer) => { this.http.get('/api/assemblies' + urlPath + '/c/' + this.getConfigurationString(configuration)) .subscribe({ next: (assembly) => { observer.next(assembly); observer.complete(); }, error: (err) => { observer.error(err); } }); }); // Use either the cache or the observable to fetch the result return this.cache.get(key, fetchAssemblyObservable, 3600).pipe(catchError((error) => { this.returned(); return of(null); }), map((result) => { this.returned(); return result; })); } getDefaultConfiguration(configurator: Configurator): Configuration { const configuration = new Configuration(); configuration.values = []; configurator.parameters.forEach((parameter) => { const parameterValue = new ParameterValue(); parameterValue.parameter = parameter.id; switch (parameter.type) { case 'quantity': const parameterQuantity = parameter as ConfigurationParameterQuantity; parameterValue.value = parameterQuantity.defaultValue + '+' + parameterQuantity.units; break; case 'enum': parameterValue.value = 'Default'; break; default: } configuration.values.push(parameterValue); }); console.log(configuration); return configuration; } getPart(rootDocumentId: string, part: ConfiguredPart, progressCallback: any): Observable<THREE.Object3D> { this.request(); // Construct the URLs to the geometry and appearance const urlPath = this.getURLPathFor(part) + '/c/' + encodeURIComponent(part.configuration) + '/p/' + encodeURIComponent(part.partId); const geometryURL = '/api/parts' + urlPath + '.stl?linkDocumentId=' + rootDocumentId; const appearanceURL = '/api/parts' + urlPath + '/appearance?linkDocumentId=' + rootDocumentId; // Construct a unique key for caching const key = 'parts' + urlPath; // Create an Observable for fetching from the API const fetchObjectObservable = new Observable((observer) => { // Get the appearance, then the geometry this.http.get(appearanceURL).subscribe({ next: (appearance) => { this.loader.load(geometryURL, geometry => { const material = this.getMaterial(appearance as Appearance); const mesh = new THREE.Mesh(geometry, material); observer.next(mesh); observer.complete(); }, (progress) => { }, (err) => observer.error(err) ); }, error: (err) => { observer.error(err); } }); }); // Use either the cache or the observable to fetch the result return this.cache.get(key, fetchObjectObservable, 3600).pipe( catchError((error) => { this.returned(); return of(null); }), map((result) => { this.returned(); return result; })); } getMaterial(appearance: Appearance): THREE.Material { if (appearance && appearance.color && appearance.opacity) { const colorString = 'rgb(' + appearance.color[0] + ',' + appearance.color[1] + ',' + appearance.color[2] + ')'; const material = new THREE.MeshPhongMaterial({ color: colorString, specular: 0x111111, shininess: 200, opacity: appearance.opacity }); return material; } const defaultMaterial = new THREE.MeshPhongMaterial({ color: 'rgb(0,0,0)', specular: 0x111111, shininess: 200, opacity: 1 }); return defaultMaterial; } getURLPathFor(document: AbstractDocumentElement): string { return this.getURLPath(document.documentId, document.wvmType, document.wvmId, document.elementId); } getURLPath(documentId: string, wvmType: WVM, wvmId: string, elementId: string): string { let url = '/d/' + documentId; switch (wvmType) { case 'Workspace': url += '/w/'; break; case 'Version': url += '/v/'; break; case 'Microversion': url += '/m/'; break; } url += wvmId + '/e/' + elementId; return url; } // CONFIGURATION UTILS METHODS getConfigurationString(configuration: Configuration) { let out = ''; configuration.values.forEach((pv) => out += (out.length === 0 ? '' : ';') + pv.parameter + '=' + pv.value); if (out.length === 0) { out = 'default'; } return encodeURIComponent(out); } private parseApiConfiguration(apiConfig: string) { const idToValueMap = {}; if (apiConfig) { for (const kvpair of apiConfig.split(';')) { const kv = kvpair.split('='); idToValueMap[kv[0]] = kv[1]; } } return idToValueMap; } getParameterIndex(parameterId: string, configuration: Configuration) { return configuration.values.findIndex(value => value.parameter === parameterId); } applyStringOverrideForDefaults(apiConfig: string, configuration: Configuration) { const idToValueMap = this.parseApiConfiguration(apiConfig); const newConfiguration = configuration; for (const [id, value] of Object.entries(idToValueMap)) { newConfiguration.values[this.getParameterIndex(id, configuration)].value = value as string; } return newConfiguration; } }
harmanpa/configurator-example
client/src/app/three/renderer/passes/transformer-pass.directive.ts
<reponame>harmanpa/configurator-example import {Directive} from '@angular/core'; import {AbstractPass} from './abstract-pass'; import {Pass} from 'three/examples/jsm/postprocessing/Pass'; import {WebGLRenderer, WebGLRenderTarget} from 'three'; import {WebGLRendererComponent} from '../webgl-renderer.component'; @Directive({ selector: '[appTransformerPass]' }) export class TransformerPassDirective extends AbstractPass<TransformPass> { constructor() { super(); } setup(renderer: WebGLRendererComponent): TransformPass { return new TransformPass(); } } class TransformPass extends Pass { render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, deltaTime: number, maskActive: boolean): void { } }
harmanpa/configurator-example
client/src/app/three-tools/orbit-controls/orbit-controls.component.ts
<gh_stars>0 /* * The MIT License * * Copyright (c) 2019 Onshape Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import {AfterViewInit, Component, Input, OnChanges, OnDestroy, forwardRef, SimpleChanges} from '@angular/core'; import {AbstractTool} from '../abstract-tool'; import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'; import * as THREE from 'three'; @Component({ selector: 'orbit-controls', templateUrl: './orbit-controls.component.html', styleUrls: ['./orbit-controls.component.scss'], providers: [{provide: AbstractTool, useExisting: forwardRef(() => OrbitControlsComponent)}] }) export class OrbitControlsComponent extends AbstractTool implements OnChanges, OnDestroy { @Input() rotateSpeed = 1.0; @Input() zoomSpeed = 1.2; @Input() zoomToFit = true; @Input() zoomToFitInitial = false; private controls: OrbitControls; constructor() { super('Orbit Controls', 'navigation', true, true); } ngOnChanges(changes: SimpleChanges) { // If the THREE.js OrbitControls are not set up yet, we do not need to update // anything as they will pick the new values from the @Input properties automatically // upon creation. if (!this.controls) { return; } if (changes['rotateSpeed']) { this.controls.rotateSpeed = this.rotateSpeed; } if (changes['zoomSpeed']) { this.controls.zoomSpeed = this.zoomSpeed; } if (changes['listeningControlElement']) { // The DOM element the OrbitControls listen on cannot be changed once an // OrbitControls object is created. We thus need to recreate it. this.controls.dispose(); this.setUpOrbitControls(); } } ngOnDestroy() { this.controls.dispose(); } private setUpOrbitControls() { console.log('Starting Orbit Controls'); this.controls = new OrbitControls( this.getRendererComponent().getCamera(), this.getRendererComponent().canvas ); this.controls.rotateSpeed = this.rotateSpeed; this.controls.zoomSpeed = this.zoomSpeed; //this.controls.addEventListener('change', this.renderer.render); if (this.zoomToFitInitial) { this.doZoomToFit(); } } onStartRendering() { super.onStartRendering(); this.setUpOrbitControls(); } public doZoomToFit() { // https://discourse.threejs.org/t/camera-zoom-to-fit-object/936/17 const camera = <THREE.PerspectiveCamera>this.getRendererComponent().getCamera(); const scene = this.getRendererComponent().getScene(); const object = scene; const offset = 1.25; const boundingBox = new THREE.Box3(); // get bounding box of object - this will be used to setup controls and camera boundingBox.setFromObject(object); const center = new THREE.Vector3(); boundingBox.getCenter(center); const size = new THREE.Vector3(); boundingBox.getSize(size); // get the max side of the bounding box (fits to width OR height as needed ) const maxDim = Math.max(size.x, size.y, size.z); const fov = camera.fov * (Math.PI / 180); let cameraZ = Math.abs(maxDim / 2 * Math.tan(fov * 2)); // Applied fifonik correction cameraZ *= offset; // zoom out a little so that objects don't fill the screen // <--- NEW CODE // Method 1 to get object's world position scene.updateMatrixWorld(); // Update world positions const objectWorldPosition = new THREE.Vector3(); objectWorldPosition.setFromMatrixPosition(object.matrixWorld); // Method 2 to get object's world position // objectWorldPosition = object.getWorldPosition(); const directionVector = camera.position.sub(objectWorldPosition); // Get vector from camera to object const unitDirectionVector = directionVector.normalize(); // Convert to unit vector camera.translateOnAxis(unitDirectionVector, cameraZ); // position = unitDirectionVector.multiplyScalar(cameraZ); // Multiply unit vector times cameraZ distance camera.lookAt(objectWorldPosition); // Look at object // ---> const minZ = boundingBox.min.z; const cameraToFarEdge = (minZ < 0) ? -minZ + cameraZ : cameraZ - minZ; camera.far = cameraToFarEdge * 3; camera.updateProjectionMatrix(); if (this.controls) { // set camera to rotate around center of loaded object this.controls.target = center; // prevent camera from zooming out far enough to create far plane cutoff this.controls.maxDistance = cameraToFarEdge * 2; } else { camera.lookAt(center); } } }
harmanpa/configurator-example
client/src/app/three/renderer/passes/abstract-pass.spec.ts
<filename>client/src/app/three/renderer/passes/abstract-pass.spec.ts import { AbstractPass } from './abstract-pass'; describe('AbstractPass', () => { it('should create an instance', () => { expect(new AbstractPass()).toBeTruthy(); }); });
harmanpa/configurator-example
client/src/app/configurator/controls/drawing-button/drawing-button.component.ts
<filename>client/src/app/configurator/controls/drawing-button/drawing-button.component.ts import {Component, Input, OnInit} from '@angular/core'; import { ConfigurableDrawing, Configuration, WVM } from '../../../../typescript-generator/configurator'; import {HttpClient} from '@angular/common/http'; import {ConfiguratorService} from '../../services/configurator.service'; @Component({ selector: 'app-drawing-button', templateUrl: './drawing-button.component.html', styleUrls: ['./drawing-button.component.scss'] }) export class DrawingButtonComponent implements OnInit { @Input() documentId: string; @Input() wvmType: WVM; @Input() wvmId: string; @Input() elementId: string; @Input() drawingElements: string[]; @Input() configuration: Configuration; drawings: ConfigurableDrawing[]; constructor(private http: HttpClient, private configuratorService: ConfiguratorService) { } ngOnInit() { this.drawings = new Array<ConfigurableDrawing>(); const baseUrl = '/api/drawings' + this.configuratorService.getURLPath(this.documentId, this.wvmType, this.wvmId, this.elementId); if (this.drawingElements) { // Use only the specified drawings this.drawingElements.forEach((de) => { this.http.get(baseUrl + '/drawing/' + de).subscribe((drawing: ConfigurableDrawing) => this.drawings.push(drawing)); }); } else { // Fetch all available drawings this.http.get(baseUrl).subscribe((drawings: ConfigurableDrawing[]) => drawings.forEach( (drawing: ConfigurableDrawing) => this.drawings.push(drawing))); } } open(drawing: ConfigurableDrawing) { const url = '/api/drawings' + this.configuratorService.getURLPath(this.documentId, this.wvmType, this.wvmId, this.elementId) + '/c/' + this.configuratorService.getConfigurationString(this.configuration) + '/drawing/' + drawing.elementId + '.pdf'; window.open(url, '_configurator_drawing'); } }
harmanpa/configurator-example
client/src/app/app-routing/app-routing.module.ts
<filename>client/src/app/app-routing/app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ConfiguratorComponent } from '../configurator/configurator/configurator.component'; const appRoutes: Routes = [{ path: 'configurator/:did/:wvm/:wvmid/e/:eid', component: ConfiguratorComponent }, { path: '**', redirectTo: 'configurator/9558507b2d8feaea012281be/v/ef47a69cee64730a99017b43/e/a8d9da8f108b44b9fa903800' }]; @NgModule({ imports: [ RouterModule.forRoot(appRoutes) ], exports: [ RouterModule ], declarations: [] }) export class AppRoutingModule { }
harmanpa/configurator-example
client/src/app/three-tools/explode/explode-transformer.ts
import {Transformer} from '../../three/transformers/transformer'; export class ExplodeTransformer extends Transformer { }
harmanpa/configurator-example
client/src/app/configurator/controls/assembly-tree/part-tree/part-tree.component.ts
<filename>client/src/app/configurator/controls/assembly-tree/part-tree/part-tree.component.ts import {Component, Input, OnInit} from '@angular/core'; import {ConfiguredPart} from '../../../../../typescript-generator/configurator'; @Component({ selector: 'app-part-tree', templateUrl: './part-tree.component.html', styleUrls: ['./part-tree.component.scss'] }) export class PartTreeComponent implements OnInit { @Input() part: ConfiguredPart; @Input() depth: number; constructor() { } ngOnInit() { } select() { } hover() { } }
harmanpa/configurator-example
client/src/app/three/renderer/webgl-renderer.component.ts
/* * The MIT License * * Copyright (c) 2017 <NAME> * Copyright (c) 2019 Onshape Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import { Component, ViewChild, ElementRef, ContentChild, HostListener, AfterViewInit, AfterContentInit, NgZone, ChangeDetectorRef, ContentChildren, EventEmitter, QueryList } from '@angular/core'; import * as THREE from 'three'; import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer'; import {SceneDirective} from '../objects/scene.directive'; import {AbstractCamera} from '../cameras/abstract-camera'; import {RendererListener} from './renderer-listener'; import {fromEvent, Subject} from 'rxjs'; import {auditTime} from 'rxjs/operators'; import {SelectionManager} from './selection-manager'; import {RenderPass} from 'three/examples/jsm/postprocessing/RenderPass'; import {AbstractObject3D} from '../objects/abstract-object-3d'; import {AbstractMaterial} from '../objects/abstract-material'; import {AbstractPass} from './passes/abstract-pass'; import {Pass} from 'three/examples/jsm/postprocessing/Pass'; @Component({ selector: 'three-webgl-renderer', templateUrl: './webgl-renderer.component.html', styleUrls: ['./webgl-renderer.component.scss'] }) export class WebGLRendererComponent implements AfterViewInit, AfterContentInit { private renderer: THREE.WebGLRenderer; private composer: EffectComposer; private viewInitialized = false; private loading: boolean; private rendererListeners: Set<RendererListener>; public progressMap: Map<String, number>; private raycaster: THREE.Raycaster; private mouse: THREE.Vector2; private preHovered: Array<THREE.Intersection>; private hovered: Array<THREE.Intersection>; private clock: THREE.Clock; private selectionManager: SelectionManager; @ViewChild('canvas', {static: true}) private canvasRef: ElementRef; public selectionChange = new Subject<AbstractObject3D<THREE.Object3D>[]>(); public hoverChange = new Subject<AbstractObject3D<THREE.Object3D>[]>(); @ContentChild(SceneDirective, {static: true}) sceneComponent: SceneDirective; @ContentChild(AbstractCamera, {static: true}) cameraComponent: AbstractCamera<THREE.Camera>; @ContentChildren(AbstractPass, {descendants: false}) passes: QueryList<AbstractPass<Pass>>; constructor(private zone: NgZone, private changeDetector: ChangeDetectorRef) { console.log('RendererComponent.constructor'); this.loading = true; this.rendererListeners = new Set<RendererListener>(); this.progressMap = new Map<String, number>(); this.mouse = new THREE.Vector2(); this.raycaster = new THREE.Raycaster(); this.hovered = new Array<THREE.Intersection>(); this.clock = new THREE.Clock(); } ngAfterViewInit() { console.log('RendererComponent.ngAfterViewInit'); this.viewInitialized = true; this.startRendering(); } ngAfterContentInit(): void { } /** * The render pane on which the scene is rendered. * Currently, only the WebGL renderer with a canvas is used in this * implementation, so this property will always be an ElementRef to the * underlying <canvas> element. * * @example This property can be used to restrict the orbit controls (i.e. the * area which is listened for mouse move and zoom events) to the rendering pane: * ``` * <three-orbit-controls [rotateSpeed]=1 [zoomSpeed]=1.2 [listeningControlElement]=mainRenderer.renderPane> * <three-renderer #mainRenderer> * ... * </three-renderer> * </three-orbit-controls> * ``` */ public get renderPane(): ElementRef { return this.canvasRef; } public get canvas(): HTMLCanvasElement { return this.canvasRef.nativeElement; } public getSize(): THREE.Vector2 { return new THREE.Vector2(this.canvas.clientWidth, this.canvas.clientHeight); } private startRendering() { console.log('RendererComponent.startRendering'); this.sceneComponent.setRendererComponent(this); this.clock.start(); this.selectionManager = new SelectionManager(this.sceneComponent, this.selectionChange, this.hoverChange); this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: true }); this.renderer.setPixelRatio(devicePixelRatio); this.renderer.setClearAlpha(0); this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight); this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; this.renderer.setClearColor(0xffffff, 1); this.renderer.autoClear = true; // Build a chain of passes for rendering this.composer = new EffectComposer(this.renderer); this.composer.addPass(new RenderPass(this.getScene(), this.getCamera())); this.passes.forEach((pass) => this.composer.addPass(pass.setup(this))); this.zone.runOutsideAngular(() => { fromEvent(this.canvasRef.nativeElement, 'mousemove').pipe(auditTime(100)).subscribe(event => { this.mouse.x = (event['clientX'] / this.canvasRef.nativeElement.width) * 2 - 1; this.mouse.y = -(event['clientY'] / this.canvasRef.nativeElement.height) * 2 + 1; this.raycaster.setFromCamera(this.mouse, this.getCamera()); const newHovered = new Array<THREE.Intersection>(); this.raycaster.intersectObjects(this.getScene().children, true, newHovered); const components = newHovered .sort((a, b) => a.distance - b.distance) .map((intersection) => intersection.object) .filter((v, i, a) => a.indexOf(v) === i); this.selectionManager.setHovered(components); }); fromEvent(this.canvasRef.nativeElement, 'click').subscribe(event => { console.log(event); this.mouse.x = (event['clientX'] / this.canvasRef.nativeElement.width) * 2 - 1; this.mouse.y = -(event['clientY'] / this.canvasRef.nativeElement.height) * 2 + 1; this.raycaster.setFromCamera(this.mouse, this.getCamera()); const newHovered = new Array<THREE.Intersection>(); this.raycaster.intersectObjects(this.getScene().children, true, newHovered); const components = newHovered.map((intersection) => intersection.object).filter((v, i, a) => a.indexOf(v) === i); if (event['ctrlKey']) { this.selectionManager.toggleSelected(components); } else { this.selectionManager.setSelected(components); } }); }); this.updateChildCamerasAspectRatio(); this.rendererListeners.forEach(rl => rl.onStartRendering()); this.zone.runOutsideAngular(() => { requestAnimationFrame(this.doRender.bind(this)); }); } private doRender() { const delta = this.clock.getDelta(); this.rendererListeners.forEach((rl) => rl.onRender(delta)); this.composer.render(delta); requestAnimationFrame(this.doRender.bind(this)); } public getCamera(): THREE.Camera { return this.cameraComponent.getCamera(); } public getScene(): THREE.Scene { if (!this.sceneComponent) { return null; } return this.sceneComponent.getObject(); } private calculateAspectRatio(): number { const height = this.canvas.clientHeight; if (height === 0) { return 0; } return this.canvas.clientWidth / this.canvas.clientHeight; } @HostListener('window:resize', ['$event']) public onResize(event: Event) { this.canvas.style.width = '100%'; this.canvas.style.height = '100%'; console.log('RendererComponent.onResize: ' + this.canvas.clientWidth + ', ' + this.canvas.clientHeight); this.updateChildCamerasAspectRatio(); this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight); this.composer.setSize(this.canvas.clientWidth, this.canvas.clientHeight); } public updateChildCamerasAspectRatio() { const aspect = this.calculateAspectRatio(); this.cameraComponent.updateAspectRatio(aspect); } public onProgress(source: string, message: string, progress: number) { /*if (source.length > 0) { setTimeout(() => { if (progress >= 1.0) { // Loading is complete, remove the progress data and render this.progressMap.delete(source); } else { this.progressMap.set(source, progress); } }); }*/ } public addListener(listener: RendererListener) { this.rendererListeners.add(listener); } public removeListener(listener: RendererListener) { this.rendererListeners.delete(listener); } }
harmanpa/configurator-example
client/src/app/three/renderer/passes/outline-pass.directive.spec.ts
import { OutlinePassDirective } from './outline-pass.directive'; describe('OutlinePassDirective', () => { it('should create an instance', () => { const directive = new OutlinePassDirective(); expect(directive).toBeTruthy(); }); });
harmanpa/configurator-example
client/src/app/configurator/controls/assembly-tree/sub-assembly-tree/sub-assembly-tree.component.ts
<gh_stars>0 import {Component, Input, OnInit} from '@angular/core'; import {SubAssembly} from '../../../../../typescript-generator/configurator'; @Component({ selector: 'app-sub-assembly-tree', templateUrl: './sub-assembly-tree.component.html', styleUrls: ['./sub-assembly-tree.component.scss'] }) export class SubAssemblyTreeComponent implements OnInit { @Input() subassembly: SubAssembly; @Input() depth: number; isCollapsed = true; constructor() { } ngOnInit() { } trackElement(index: number, element: any) { return element ? element.instanceId : null; } }
harmanpa/configurator-example
client/src/app/configurator/configurator.module.ts
<gh_stars>0 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ThreeToolsModule } from '../three-tools/three-tools.module'; import { ThreeModule } from '../three/three.module'; import { ConfiguratorComponent } from './configurator/configurator.component'; import { ConfiguredPartDirective } from './geometry/configured-part.directive'; import { ConfiguredAssemblyComponent } from './geometry/configured-assembly/configured-assembly.component'; import { SubAssemblyComponent } from './geometry/sub-assembly/sub-assembly.component'; import { ParameterEnumComponent } from './controls/parameter-enum/parameter-enum.component'; import { ParameterQuantityComponent } from './controls/parameter-quantity/parameter-quantity.component'; import { HttpClientModule } from '@angular/common/http'; import { NgSelectModule } from '@ng-select/ng-select'; import { FormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms'; import { Ng5SliderModule } from 'ng5-slider'; import { ProgressComponent } from './controls/progress/progress.component'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { library } from '@fortawesome/fontawesome-svg-core'; import { fas } from '@fortawesome/free-solid-svg-icons'; import { ExportButtonComponent } from './controls/export-button/export-button.component'; import { NgbDropdownModule, NgbTooltipModule, NgbProgressbarModule } from '@ng-bootstrap/ng-bootstrap'; import { DrawingButtonComponent } from './controls/drawing-button/drawing-button.component'; import { OnshapeButtonComponent } from './controls/onshape-button/onshape-button.component'; import { AssemblyTreeComponent } from './controls/assembly-tree/assembly-tree.component'; import { SubAssemblyTreeComponent } from './controls/assembly-tree/sub-assembly-tree/sub-assembly-tree.component'; import { PartTreeComponent } from './controls/assembly-tree/part-tree/part-tree.component'; import {NgbCollapseModule} from '@ng-bootstrap/ng-bootstrap'; import { MatButtonModule, MatCheckboxModule, MatFormFieldModule, MatIconModule, MatListModule, MatOptionModule, MatSelectModule, MatSidenavModule, MatToolbarModule } from "@angular/material"; import {SidebarModule} from "ng-sidebar"; @NgModule({ declarations: [ ConfiguratorComponent, ConfiguredPartDirective, ConfiguredAssemblyComponent, SubAssemblyComponent, ParameterEnumComponent, ParameterQuantityComponent, ProgressComponent, ExportButtonComponent, DrawingButtonComponent, OnshapeButtonComponent, AssemblyTreeComponent, SubAssemblyTreeComponent, PartTreeComponent ], exports: [ ConfiguratorComponent, ConfiguredPartDirective, ConfiguredAssemblyComponent, SubAssemblyComponent, ParameterEnumComponent, ParameterQuantityComponent ], imports: [ CommonModule, ThreeToolsModule, ThreeModule, HttpClientModule, FormsModule, ReactiveFormsModule, NgSelectModule, Ng5SliderModule, FontAwesomeModule, NgbDropdownModule, NgbTooltipModule, NgbProgressbarModule, NgbCollapseModule, MatSidenavModule, MatFormFieldModule, MatOptionModule, MatSelectModule, MatButtonModule, MatToolbarModule, MatCheckboxModule, MatListModule, MatIconModule, SidebarModule ] }) export class ConfiguratorModule { constructor() { library.add(fas); } }
harmanpa/configurator-example
client/src/app/three-tools/explode/explode-transformer.spec.ts
import { ExplodeTransformer } from './explode-transformer'; describe('ExplodeTransformer', () => { it('should create an instance', () => { expect(new ExplodeTransformer()).toBeTruthy(); }); });
harmanpa/configurator-example
client/src/app/three/renderer/passes/fxaa-pass.directive.ts
<reponame>harmanpa/configurator-example<filename>client/src/app/three/renderer/passes/fxaa-pass.directive.ts<gh_stars>0 import { Directive } from '@angular/core'; import {AbstractPass} from './abstract-pass'; import {WebGLRendererComponent} from '../webgl-renderer.component'; import {ShaderPass} from 'three/examples/jsm/postprocessing/ShaderPass'; import {FXAAShader} from 'three/examples/jsm/shaders/FXAAShader'; @Directive({ selector: 'three-fxaa-pass' }) export class FxaaPassDirective extends AbstractPass<ShaderPass> { shaderPass: ShaderPass; constructor() { super(); } setup(renderer: WebGLRendererComponent): ShaderPass { this.shaderPass = new ShaderPass(FXAAShader); //this.shaderPass.uniforms[ 'resolution' ].value.set( 1 / renderer.getSize().x, 1 / renderer.getSize().y ); this.shaderPass.uniforms[ 'resolution' ].value.set( 1 / window.innerWidth, 1 / window.innerHeight ); return this.shaderPass; } }
harmanpa/configurator-example
client/src/app/configurator/geometry/configured-part.directive.ts
<reponame>harmanpa/configurator-example import {Directive, forwardRef, Input, OnChanges, SimpleChanges} from '@angular/core'; import {AbstractObject3D} from '../../three/objects/abstract-object-3d'; import * as THREE from 'three'; import { ConfiguredPart } from '../../../typescript-generator/configurator'; import {ConfiguratorService} from '../services/configurator.service'; import {Observable} from 'rxjs'; @Directive({ selector: 'app-configured-part', providers: [{provide: AbstractObject3D, useExisting: forwardRef(() => ConfiguredPartDirective)}] }) export class ConfiguredPartDirective extends AbstractObject3D<THREE.Object3D> implements OnChanges { @Input() rootDocumentId: string; @Input() part: ConfiguredPart; protected currentLoadedModelObject: THREE.Object3D | undefined; constructor(private configuratorService: ConfiguratorService) { super(); } id(): string { return this.part.instanceId; } protected afterInit(): void { this.matrix = this.part.transform; this.transposeMatrix = false; this.load().subscribe({ next: newModel => { if (this.currentLoadedModelObject) { this.removeChild(this.currentLoadedModelObject); } const mesh = newModel as THREE.Mesh; const geometry = mesh.geometry.clone(); this.currentLoadedModelObject = new THREE.Mesh(geometry, mesh.material); this.addChild(this.currentLoadedModelObject); }, error: (err) => console.error(err) }); } ngOnChanges(changes: SimpleChanges): void { if (changes.part) { if (!changes.part.previousValue) { console.log('Reloading part'); this.afterInit(); return; } if (changes.part.currentValue.transform.some((v, i) => v !== changes.part.previousValue.transform[i])) { // Transform has changed this.matrix = changes.part.currentValue.transform; this.applyMatrix(); } if (changes.part.currentValue.documentId !== changes.part.previousValue.documentId || changes.part.currentValue.wvmType !== changes.part.previousValue.wvmType || changes.part.currentValue.wvmId !== changes.part.previousValue.wvmId || changes.part.currentValue.elementId !== changes.part.previousValue.elementId || changes.part.currentValue.partId !== changes.part.previousValue.partId || changes.part.currentValue.configuration !== changes.part.previousValue.configuration) { // Part has changed this.load().subscribe({ next: newModel => { if (this.currentLoadedModelObject) { this.removeChild(this.currentLoadedModelObject); } const mesh = newModel as THREE.Mesh; const geometry = mesh.geometry.clone(); this.currentLoadedModelObject = new THREE.Mesh(geometry, mesh.material); this.addChild(this.currentLoadedModelObject); }, error: (err) => console.error(err) }); } } } protected newObject3DInstance(): THREE.Object3D { return new THREE.Object3D(); } protected load(): Observable<THREE.Object3D> { return this.configuratorService.getPart(this.rootDocumentId, this.part, (progress) => { this.onProgress('Loading...', progress.loaded / progress.total); }); } }
harmanpa/configurator-example
client/src/app/configurator/controls/assembly-tree/assembly-tree.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {ConfiguredAssembly} from '../../../../typescript-generator/configurator'; @Component({ selector: 'app-assembly-tree', templateUrl: './assembly-tree.component.html', styleUrls: ['./assembly-tree.component.scss'] }) export class AssemblyTreeComponent implements OnInit { @Input() assembly: ConfiguredAssembly; constructor() { } ngOnInit() { } trackElement(index: number, element: any) { return element ? element.instanceId : null; } }
harmanpa/configurator-example
client/src/app/three/renderer/passes/abstract-pass.ts
<filename>client/src/app/three/renderer/passes/abstract-pass.ts import { Pass } from 'three/examples/jsm/postprocessing/Pass'; import {WebGLRendererComponent} from '../webgl-renderer.component'; export abstract class AbstractPass<T extends Pass> { public abstract setup(renderer: WebGLRendererComponent): T; }
harmanpa/configurator-example
client/src/app/configurator/configurator/configurator.component.ts
import {Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core'; import {AbstractDocumentElement, Appearance, Configuration, ConfigurationParameter, ConfigurationParameterEnum, ConfigurationParameterQuantity, Configurator, ConfiguredAssembly, ConfiguredPart, EnumOption, ParameterValue, SubAssembly, WVM} from '../../../typescript-generator/configurator'; import {Observable} from 'rxjs'; import {ConfiguratorService } from '../services/configurator.service'; import * as _ from 'lodash'; import {ActivatedRoute} from '@angular/router'; @Component({ selector: 'app-configurator', templateUrl: './configurator.component.html', styleUrls: ['./configurator.component.scss'] }) export class ConfiguratorComponent implements OnInit, OnChanges { showFiller = false; @Input() documentId: string; @Input() wvmType: WVM; @Input() wvmId: string; @Input() elementId: string; @Input() drawingElements: string[]; @Output() configurationChange = new EventEmitter<Configuration>(true); configurator$: Observable<Configurator>; configurator: Configurator; configuredAssembly: ConfiguredAssembly; apiConfiguration: string; configuration: Configuration; appliedConfiguration: Configuration; defaultConfiguration: Configuration; pi = Math.PI; halfpi = -1 * this.pi / 2; progress: number; inProgress: boolean; isDefault: boolean; changed: boolean; constructor(private configuratorService: ConfiguratorService, private route: ActivatedRoute) { this.configuredAssembly = null; } ngOnInit() { if (this.route.snapshot.paramMap.get('did')) { this.documentId = this.route.snapshot.paramMap.get('did'); switch (this.route.snapshot.paramMap.get('wvm')) { case 'w': this.wvmType = 'Workspace'; break; case 'v': this.wvmType = 'Version'; break; case 'm': this.wvmType = 'Microversion'; break; } this.wvmType = this.wvmType as WVM; this.wvmId = this.route.snapshot.paramMap.get('wvmid'); this.elementId = this.route.snapshot.paramMap.get('eid'); this.apiConfiguration = this.route.snapshot.queryParamMap.get('configuration'); } console.log(this.drawingElements); this.inProgress = false; this.progress = 100; this.configuratorService.progressChange.subscribe((p) => this.progress = p); this.configurator$ = this.configuratorService.getConfigurator(this.documentId, this.wvmType, this.wvmId, this.elementId); this.configurator$.subscribe({ next: (configurator) => { this.configurator = configurator; this.defaultConfiguration = this.configuratorService.applyStringOverrideForDefaults(this.apiConfiguration, this.configuratorService.getDefaultConfiguration(configurator)); this.configuration = _.cloneDeep(this.defaultConfiguration); this.appliedConfiguration = _.cloneDeep(this.defaultConfiguration); this.updateAssembly(); }, error: (err) => { console.log(err); }}); this.configurationChange.subscribe((configuration) => { this.changed = !_.isEqual(this.configuration, this.appliedConfiguration); this.isDefault = _.isEqual(this.appliedConfiguration, this.defaultConfiguration); }); } ngOnChanges(changes: SimpleChanges): void { //this.ngOnInit(); } updateAssembly() { console.log('Updating assembly'); this.inProgress = true; this.configuratorService.getAssembly(this.configurator, this.configuration) .subscribe({next: (configuredAssembly) => { this.configuredAssembly = configuredAssembly; this.appliedConfiguration = _.cloneDeep(this.configuration); this.configuratorService.progressChange.subscribe((prog) => { if (prog >= 100) { this.inProgress = false; this.changed = !_.isEqual(this.configuration, this.appliedConfiguration); this.isDefault = _.isEqual(this.appliedConfiguration, this.defaultConfiguration); } }); }, error: (err) => { console.log(err); this.inProgress = false; this.changed = !_.isEqual(this.configuration, this.appliedConfiguration); this.isDefault = _.isEqual(this.appliedConfiguration, this.defaultConfiguration); }}); } parameterValueChange(parameterValue: ParameterValue) { this.configurationChange.emit(this.configuration); } quantityParameter(parameter: ConfigurationParameter): ConfigurationParameterQuantity { return parameter as ConfigurationParameterQuantity; } enumParameter(parameter: ConfigurationParameter): ConfigurationParameterEnum { return parameter as ConfigurationParameterEnum; } undo() { this.configuration = _.cloneDeep(this.appliedConfiguration); this.configurationChange.emit(this.configuration); } home() { this.configuration = _.cloneDeep(this.defaultConfiguration); this.configurationChange.emit(this.configuration); } }
harmanpa/configurator-example
client/src/app/three/renderer/passes/outline-pass.directive.ts
import {Directive, forwardRef} from '@angular/core'; import {AbstractPass} from './abstract-pass'; import {OutlinePass} from 'three/examples/jsm/postprocessing/OutlinePass'; import {WebGLRendererComponent} from '../webgl-renderer.component'; import {AbstractObject3D} from '../../objects/abstract-object-3d'; import * as THREE from 'three'; @Directive({ selector: 'three-outline-pass', providers: [{provide: AbstractPass, useExisting: forwardRef(() => OutlinePassDirective)}] }) export class OutlinePassDirective extends AbstractPass<OutlinePass> { outlinePass: OutlinePass; constructor() { super(); } setup(renderer: WebGLRendererComponent): OutlinePass { this.outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth, window.innerHeight), renderer.getScene(), renderer.getCamera()); // this.outlinePass.visibleEdgeColor = new THREE.Color(1,0,0); // this.outlinePass = new OutlinePass(renderer.getSize(), renderer.getScene(), renderer.getCamera()); renderer.hoverChange.subscribe((hovered: AbstractObject3D<THREE.Object3D>[]) => { this.outlinePass.selectedObjects = hovered.map((component) => component.getObject()); }); return this.outlinePass; } }
harmanpa/configurator-example
client/src/app/three/renderer/passes/fxaa-pass.directive.spec.ts
import { FxaaPassDirective } from './fxaa-pass.directive'; describe('FxaaPassDirective', () => { it('should create an instance', () => { const directive = new FxaaPassDirective(); expect(directive).toBeTruthy(); }); });
harmanpa/configurator-example
client/src/app/three/transformers/transformer.spec.ts
import { Transformer } from './transformer'; describe('Transformer', () => { it('should create an instance', () => { expect(new Transformer()).toBeTruthy(); }); });
harmanpa/configurator-example
client/src/app/three/objects/loaders/abstract-model-loader.ts
/* * The MIT License * * Copyright (c) 2017 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import { AfterViewInit, forwardRef, Input, OnDestroy } from '@angular/core'; import {AbstractObject3D} from '../abstract-object-3d'; import {WebGLRendererComponent} from '../../renderer/webgl-renderer.component'; import * as THREE from 'three'; /** * Helper parent class for model loader directives. * * @see ObjectLoaderDirective * @see ObjLoaderDirective * @see StlLoaderDirective */ export abstract class AbstractModelLoader extends AbstractObject3D<THREE.Object3D> implements OnDestroy { private _model: string; /** * Flag to signal whether the parent class instance AbstractObject3D called the * overwritten method {@link ModelLoaderDirective#afterInit} yet. * * Unless that method was called, no methods and properties of {@link AbstractObject3D} * may be safely accessed, especially {@link AbstractObject3D#addChild} and * {@link AbstractObject3D.renderer}. */ private parentInitialized = false; protected currentLoadedModelObject: THREE.Object3D | undefined; /** * Load the model object. * * Some loaders (e.g. ColladaLoader) also provide other model information * upon loading besides the "raw" model object/scene. In these cases * implementing child classes are indeed supposed to return the "raw" model * object. * The data source (usually a URI, although child classes are free to implement * other means as well) from which the model shall be loaded can be obtained by * {@link ModelLoaderDirective.model}. */ protected abstract async loadModelObject(): Promise<THREE.Object3D>; /** * The model data source (usually a URI). * Settings this property only hides the previous model upon successful * loading of the new one. This especially means that if the new data source * is invalid, the old model will *not* be removed from the scene. */ @Input() public set model(newModelUrl: string) { this._model = newModelUrl; // Delay model loading until the parent has been initialized, // so that we can call addChild(). if (!this.parentInitialized) { return; } this.loadModelObject().then(newModel => { if (this.currentLoadedModelObject) { this.removeChild(this.currentLoadedModelObject); } this.currentLoadedModelObject = newModel; this.addChild(newModel); }).catch(err => { console.error(err); }); } /** * The current model data source (usually a URI). */ public get model() { return this._model; } protected afterInit() { this.parentInitialized = true; // Trigger model acquisition now that the parent has been initialized. this.model = this.model; } ngOnDestroy(): void { if (this.currentLoadedModelObject) { this.removeChild(this.currentLoadedModelObject); } } protected id(): string { return this._model; } protected newObject3DInstance(): THREE.Object3D { return new THREE.Object3D(); } }
matcharr/nestjs-api-blog
src/posts/entities/post.entity.ts
import { Column, CreateDateColumn, Entity, PrimaryColumn, UpdateDateColumn, } from 'typeorm'; @Entity('posts') export class PostsEntity { @PrimaryColumn({ generated: true }) id: number; @Column() content: string; @Column() title: string; @CreateDateColumn() createdAt: Date; @UpdateDateColumn() updatedAt: Date; }
matcharr/nestjs-api-blog
src/posts/posts.service.ts
import { Injectable } from '@nestjs/common'; import { CreatePostDto } from './dto/create-post.dto'; import { UpdatePostDto } from './dto/update-post.dto'; import { PostsEntity } from './entities/post.entity'; import { Repository, Connection } from 'typeorm'; @Injectable() export class PostsService { private _postsRespository: Repository<PostsEntity>; constructor(private _connection: Connection) { this._postsRespository = this._connection.getRepository(PostsEntity); } async create(createPostDto: CreatePostDto) { const newPost = this._postsRespository.create(); newPost.title = createPostDto.title; newPost.content = createPostDto.content; await this._postsRespository.save(newPost); return newPost; } async findAll() { return await this._postsRespository.find(); } async findOne(id: number) { return await this._postsRespository.findOne(id); } async update(id: number, updatePostDto: UpdatePostDto) { const post = await this._postsRespository.findOneOrFail(id); post.content = updatePostDto.content; post.title = updatePostDto.title; await this._postsRespository.save(post); return post; } async remove(id: number) { await this._postsRespository.delete(id); } }
matcharr/nestjs-api-blog
src/app.module.ts
<filename>src/app.module.ts import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { TypeOrmModule } from '@nestjs/typeorm'; import { TypeOrmConfigService } from './persistence/typeorm-config.service'; import { PostsModule } from './posts/posts.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, envFilePath: '.development.env', }), TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService, }), PostsModule, ], }) export class AppModule {}
matcharr/nestjs-api-blog
src/persistence/typeorm-config.service.ts
<filename>src/persistence/typeorm-config.service.ts import { Injectable } from '@nestjs/common'; import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm'; import { ConfigService } from '@nestjs/config'; @Injectable() export class TypeOrmConfigService implements TypeOrmOptionsFactory { constructor(private _configService: ConfigService) {} createTypeOrmOptions(): TypeOrmModuleOptions { return { type: 'postgres', host: this._configService.get('DB_HOST'), port: +this._configService.get<number>('DB_PORT'), username: this._configService.get('DB_USERNAME'), password: this._<PASSWORD>('DB_PASSWORD'), database: this._configService.get('DB'), entities: [__dirname + '/../**/*.entity{.ts,.js}'], synchronize: !!this._configService.get('DB_SYNCHRONIZE'), logging: !!this._configService.get('DB_LOGGING'), autoLoadEntities: !!this._configService.get('DB_AUTOLOADENTITIES'), }; } }
rojinva/tfjs-models_Tensorflow
coco-ssd/src/index.ts
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs'; import {CLASSES} from './classes'; const BASE_PATH = 'https://storage.googleapis.com/tfjs-models/savedmodel/'; export type ObjectDetectionBaseModel = 'ssd_mobilenet_v1'|'ssd_mobilenet_v2'|'ssdlite_mobilenet_v2'; export interface DetectedObject { bbox: [number, number, number, number]; // [x, y, width, height] class: string; score: number; } export async function load( base: ObjectDetectionBaseModel = 'ssdlite_mobilenet_v2') { if (tf == null) { throw new Error( `Cannot find TensorFlow.js. If you are using a <script> tag, please ` + `also include @tensorflow/tfjs on the page before using this model.`); } if (['ssd_mobilenet_v1', 'ssd_mobilenet_v2', 'ssdlite_mobilenet_v2'].indexOf( base) === -1) { throw new Error( `ObjectDetection constructed with invalid base model ` + `${base}. Valid names are 'ssd_mobilenet_v1',` + ` 'ssd_mobilenet_v2' and 'ssdlite_mobilenet_v2'.`); } const objectDetection = new ObjectDetection(base); await objectDetection.load(); return objectDetection; } export class ObjectDetection { private modelPath: string; private weightPath: string; private model: tf.FrozenModel; constructor(base: ObjectDetectionBaseModel) { this.modelPath = `${BASE_PATH}${base}/` + `tensorflowjs_model.pb`; this.weightPath = `${BASE_PATH}${base}/` + `weights_manifest.json`; } async load() { this.model = await tf.loadFrozenModel(this.modelPath, this.weightPath); // Warmup the model. const result = await this.model.executeAsync(tf.zeros([1, 300, 300, 3])) as tf.Tensor[]; result.map(async (t) => await t.data()); result.map(async (t) => t.dispose()); } /** * Infers through the model. * * @param img The image to classify. Can be a tensor or a DOM element image, * video, or canvas. * @param maxNumBoxes The maximum number of bounding boxes of detected * objects. There can be multiple objects of the same class, but at different * locations. Defaults to 20. */ private async infer( img: tf.Tensor3D|ImageData|HTMLImageElement|HTMLCanvasElement| HTMLVideoElement, maxNumBoxes: number): Promise<DetectedObject[]> { const batched = tf.tidy(() => { if (!(img instanceof tf.Tensor)) { img = tf.fromPixels(img); } // Reshape to a single-element batch so we can pass it to executeAsync. return img.expandDims(0); }) const height = batched.shape[1]; const width = batched.shape[2]; // model returns two tensors: // 1. box classification score with shape of [1, 1917, 90] // 2. box location with shape of [1, 1917, 1, 4] // where 1917 is the number of box detectors, 90 is the number of classes. // and 4 is the four coordinates of the box. const result = await this.model.executeAsync(batched) as tf.Tensor[]; const scores = result[0].dataSync() as Float32Array; const boxes = result[1].dataSync() as Float32Array; // clean the webgl tensors batched.dispose(); tf.dispose(result); const [maxScores, classes] = this.calculateMaxScores(scores, result[0].shape[1], result[0].shape[2]); const prevBackend = tf.getBackend(); // run post process in cpu tf.setBackend('cpu'); const indexTensor = tf.tidy(() => { const boxes2 = tf.tensor2d(boxes, [result[1].shape[1], result[1].shape[3]]); return tf.image.nonMaxSuppression( boxes2, maxScores, maxNumBoxes, 0.5, 0.5); }); const indexes = indexTensor.dataSync() as Float32Array; indexTensor.dispose(); // restore previous backend tf.setBackend(prevBackend); return this.buildDetectedObjects( width, height, boxes, maxScores, indexes, classes); } private buildDetectedObjects( width: number, height: number, boxes: Float32Array, scores: number[], indexes: Float32Array, classes: number[]): DetectedObject[] { const count = indexes.length; const objects: DetectedObject[] = []; for (let i = 0; i < count; i++) { const bbox = []; for (let j = 0; j < 4; j++) { bbox[j] = boxes[indexes[i] * 4 + j]; } const minY = bbox[0] * height; const minX = bbox[1] * width; const maxY = bbox[2] * height; const maxX = bbox[3] * width; bbox[0] = minX; bbox[1] = minY; bbox[2] = maxX - minX; bbox[3] = maxY - minY; objects.push({ bbox: bbox as [number, number, number, number], class: CLASSES[classes[indexes[i]] + 1].displayName, score: scores[indexes[i]] }); } return objects; } private calculateMaxScores( scores: Float32Array, numBoxes: number, numClasses: number): [number[], number[]] { const maxes = []; const classes = []; for (let i = 0; i < numBoxes; i++) { let max = Number.MIN_VALUE; let index = -1; for (let j = 0; j < numClasses; j++) { if (scores[i * numClasses + j] > max) { max = scores[i * numClasses + j]; index = j; } } maxes[i] = max; classes[i] = index; } return [maxes, classes]; } /** * Detect objects for an image returning a list of bounding boxes with * assocated class and score. * * @param img The image to detect objects from. Can be a tensor or a DOM * element image, video, or canvas. * @param maxNumBoxes The maximum number of bounding boxes of detected * objects. There can be multiple objects of the same class, but at different * locations. Defaults to 20. * */ async detect( img: tf.Tensor3D|ImageData|HTMLImageElement|HTMLCanvasElement| HTMLVideoElement, maxNumBoxes = 20): Promise<DetectedObject[]> { return this.infer(img, maxNumBoxes); } /** * Dispose the tensors allocated by the model. You should call this when you * are done with the model. */ dispose() { if (this.model) { this.model.dispose(); } } }
rojinva/tfjs-models_Tensorflow
speech-commands/training/cli.ts
<reponame>rojinva/tfjs-models_Tensorflow /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ // Load the binding import '@tensorflow/tfjs-node'; import chalk from 'chalk'; import * as ora from 'ora'; import * as Vorpal from 'vorpal'; import {AudioModel} from './audio_model'; import {Dataset} from './dataset'; import {WavFileFeatureExtractor} from './wav_file_feature_extractor'; // tslint:disable-next-line:no-any (global as any).AudioContext = class AudioContext {}; export const MODEL_SHAPE = [98, 40, 1]; export const labelsMsg = [ {type: 'input', name: 'labels', message: 'Enter labels (seperate by comma)'} ]; export const trainingMsg = [ {type: 'input', name: 'dir', message: 'Enter file directory'}, {type: 'input', name: 'label', message: 'Enter label for the directory'} ]; export const filenameMsg = [{ type: 'input', name: 'filename', message: 'Enter target filename for the model' }]; let model: AudioModel; let labels: string[]; const vorpal = new Vorpal(); let spinner = ora(); vorpal.command('create_model [labels...]') .alias('c') .description('create the audio model') .action((args, cb) => { console.log(args.labels); labels = args.labels as string[]; model = new AudioModel( MODEL_SHAPE, labels, new Dataset(labels.length), new WavFileFeatureExtractor()); cb(); }); vorpal .command( 'load_dataset all <dir>', 'Load all the data from the root directory by the labels') .alias('la') .action((args) => { spinner.start('load dataset ...'); return model .loadAll( args.dir as string, (text: string, finished?: boolean) => { if (finished) { spinner.succeed(text); } else { spinner.start(); spinner.text = text; spinner.render(); } }) .then(() => spinner.stop()); }); vorpal .command( 'load_dataset <dir> <label>', 'Load the dataset from the directory with the label') .alias('l') .action((args) => { spinner = ora('creating tensors ...'); spinner.start(); return model .loadData( args.dir as string, args.label as string, (text: string) => { // console.log(text); spinner.text = text; spinner.render(); }) .then(() => spinner.stop(), (err) => { spinner.fail(`failed to load: ${err}`); }); }); vorpal.command('dataset size', 'Show the size of the dataset') .alias('d') .action((args, cb) => { console.log(chalk.green(`dataset size = ${model.size()}`)); cb(); }); vorpal.command('train [epoch]') .alias('t') .description('train all audio dataset') .action((args) => { spinner = ora('training models ...').start(); return model .train(parseInt(args.epoch as string, 10) || 20, { onBatchEnd: async (batch, logs) => { spinner.text = chalk.green(`loss: ${logs.loss.toFixed(5)}`); spinner.render(); }, onEpochEnd: async (epoch, logs) => { spinner.succeed(chalk.green( `epoch: ${epoch}, loss: ${logs.loss.toFixed(5)}` + `, accuracy: ${logs.acc.toFixed(5)}` + `, validation accuracy: ${logs.val_acc.toFixed(5)}`)); spinner.start(); } }) .then(() => spinner.stop()); }); vorpal.command('save_model <filename>') .alias('s') .description('save the audio model') .action((args) => { spinner.start(`saving to ${args.filename} ...`); return model.save(args.filename as string).then(() => { spinner.succeed(`${args.filename} saved.`); }, () => spinner.fail(`failed to save ${args.filename}`)); }); vorpal.show();
rojinva/tfjs-models_Tensorflow
posenet/src/util_test.ts
/** * @license * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import {getValidResolution} from './util'; describe('util.getValidResolution', () => { it('returns an odd value', () => { expect(getValidResolution(0.5, 545, 32) % 2).toEqual(1); expect(getValidResolution(0.5, 545, 16) % 2).toEqual(1); expect(getValidResolution(0.5, 545, 8) % 2).toEqual(1); expect(getValidResolution(0.845, 242, 8) % 2).toEqual(1); expect(getValidResolution(0.421, 546, 16) % 2).toEqual(1); }); it('returns a value that when 1 is subtracted by it is ' + 'divisible by the output stride', () => { const outputStride = 32; const imageSize = 562; const scaleFactor = 0.63; const resolution = getValidResolution(scaleFactor, imageSize, outputStride); expect((resolution - 1) % outputStride).toEqual(0); }); });
rojinva/tfjs-models_Tensorflow
posenet/src/multiPose/decodePose.ts
<reponame>rojinva/tfjs-models_Tensorflow<gh_stars>0 /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import {NumberTuple, partIds, partNames, poseChain} from '../keypoints'; import {Keypoint, PartWithScore, TensorBuffer3D, Vector2D} from '../types'; import {clamp, getOffsetPoint} from './util'; import {addVectors, getImageCoords} from './util'; const parentChildrenTuples: NumberTuple[] = poseChain.map( ([parentJoinName, childJoinName]): NumberTuple => ([partIds[parentJoinName], partIds[childJoinName]])); const parentToChildEdges: number[] = parentChildrenTuples.map(([, childJointId]) => childJointId); const childToParentEdges: number[] = parentChildrenTuples.map(([ parentJointId, ]) => parentJointId); function getDisplacement( edgeId: number, point: Vector2D, displacements: TensorBuffer3D): Vector2D { const numEdges = displacements.shape[2] / 2; return { y: displacements.get(point.y, point.x, edgeId), x: displacements.get(point.y, point.x, numEdges + edgeId) }; } function getStridedIndexNearPoint( point: Vector2D, outputStride: number, height: number, width: number): Vector2D { return { y: clamp(Math.round(point.y / outputStride), 0, height - 1), x: clamp(Math.round(point.x / outputStride), 0, width - 1) }; } /** * We get a new keypoint along the `edgeId` for the pose instance, assuming * that the position of the `idSource` part is already known. For this, we * follow the displacement vector from the source to target part (stored in * the `i`-t channel of the displacement tensor). */ function traverseToTargetKeypoint( edgeId: number, sourceKeypoint: Keypoint, targetKeypointId: number, scoresBuffer: TensorBuffer3D, offsets: TensorBuffer3D, outputStride: number, displacements: TensorBuffer3D): Keypoint { const [height, width] = scoresBuffer.shape; // Nearest neighbor interpolation for the source->target displacements. const sourceKeypointIndices = getStridedIndexNearPoint( sourceKeypoint.position, outputStride, height, width); const displacement = getDisplacement(edgeId, sourceKeypointIndices, displacements); const displacedPoint = addVectors(sourceKeypoint.position, displacement); const displacedPointIndices = getStridedIndexNearPoint(displacedPoint, outputStride, height, width); const offsetPoint = getOffsetPoint( displacedPointIndices.y, displacedPointIndices.x, targetKeypointId, offsets); const score = scoresBuffer.get( displacedPointIndices.y, displacedPointIndices.x, targetKeypointId); const targetKeypoint = addVectors( { x: displacedPointIndices.x * outputStride, y: displacedPointIndices.y * outputStride }, {x: offsetPoint.x, y: offsetPoint.y}); return {position: targetKeypoint, part: partNames[targetKeypointId], score}; } /** * Follows the displacement fields to decode the full pose of the object * instance given the position of a part that acts as root. * * @return An array of decoded keypoints and their scores for a single pose */ export function decodePose( root: PartWithScore, scores: TensorBuffer3D, offsets: TensorBuffer3D, outputStride: number, displacementsFwd: TensorBuffer3D, displacementsBwd: TensorBuffer3D): Keypoint[] { const numParts = scores.shape[2]; const numEdges = parentToChildEdges.length; const instanceKeypoints: Keypoint[] = new Array(numParts); // Start a new detection instance at the position of the root. const {part: rootPart, score: rootScore} = root; const rootPoint = getImageCoords(rootPart, outputStride, offsets); instanceKeypoints[rootPart.id] = { score: rootScore, part: partNames[rootPart.id], position: rootPoint }; // Decode the part positions upwards in the tree, following the backward // displacements. for (let edge = numEdges - 1; edge >= 0; --edge) { const sourceKeypointId = parentToChildEdges[edge]; const targetKeypointId = childToParentEdges[edge]; if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) { instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint( edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsBwd); } } // Decode the part positions downwards in the tree, following the forward // displacements. for (let edge = 0; edge < numEdges; ++edge) { const sourceKeypointId = childToParentEdges[edge]; const targetKeypointId = parentToChildEdges[edge]; if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) { instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint( edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsFwd); } } return instanceKeypoints; }
rojinva/tfjs-models_Tensorflow
speech-commands/utils/dataset.ts
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs'; /** * A dataset for webcam controls which allows the user to add example Tensors * for particular labels. This object will concat them into two large xs and ys. */ export class Dataset { xs: tf.Tensor[]; ys: tf.Tensor; constructor(public numClasses: number) {} /** * Adds an example to the controller dataset. * @param {Tensor} example A tensor representing the example. * It can be an image, an activation, or any other type of Tensor. * @param {number} label The label of the example. Should be an number. */ addExample(example: tf.Tensor|tf.Tensor[], label: number) { example = Array.isArray(example) ? example : [example]; // One-hot encode the label. const y = tf.tidy(() => tf.oneHot(tf.tensor1d([label]).toInt(), this.numClasses)); if (this.xs == null) { // For the first example that gets added, keep example and y so that the // Dataset owns the memory of the inputs. This makes sure that // if addExample() is called in a tf.tidy(), these Tensors will not get // disposed. this.xs = example.map(tensor => tf.keep(tensor)); this.ys = tf.keep(y); } else { const oldX = this.xs; this.xs = example.map( (tensor, index) => tf.keep(this.xs[index].concat(tensor, 0))); const oldY = this.ys; this.ys = tf.keep(oldY.concat(y, 0)); oldX.forEach(tensor => tensor.dispose()); oldY.dispose(); y.dispose(); } } }
rojinva/tfjs-models_Tensorflow
speech-commands/utils/types.ts
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import {InferenceModel} from '@tensorflow/tfjs'; export interface Params { inputBufferLength?: number; bufferLength?: number; hopLength?: number; duration?: number; fftSize?: number; melCount?: number; targetSr?: number; isMfccEnabled?: boolean; } export interface FeatureExtractor { config(params: Params): void; start(samples?: Float32Array): Promise<Float32Array[]>|void; stop(): void; getFeatures(): Float32Array[]; getImages(): Float32Array[]; } export enum ModelType { FROZEN_MODEL = 0, FROZEN_MODEL_NATIVE, TF_MODEL } export const BUFFER_LENGTH = 1024; export const HOP_LENGTH = 444; export const MEL_COUNT = 40; export const EXAMPLE_SR = 44100; export const DURATION = 1.0; export const IS_MFCC_ENABLED = true; export const MIN_SAMPLE = 3; export const DETECTION_THRESHOLD = 0.5; export const SUPPRESSION_TIME = 500; export const MODELS: {[key: number]: InferenceModel} = {};
rojinva/tfjs-models_Tensorflow
speech-commands/utils/circular_audio_buffer.ts
<filename>speech-commands/utils/circular_audio_buffer.ts /** * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * Save Float32Array in arbitrarily sized chunks. * Load Float32Array in arbitrarily sized chunks. * Determine if there's enough data to grab a certain amount. */ export class CircularAudioBuffer { buffer: Float32Array; // The index that we are currently full up to. New data is written from // [currentIndex + 1, maxLength]. Data can be read from [0, currentIndex]. currentIndex: number; constructor(maxLength: number) { this.buffer = new Float32Array(maxLength); this.currentIndex = 0; } /** * Add a new buffer of data. Called when we get new audio input samples. */ addBuffer(newBuffer: Float32Array) { // Do we have enough data in this buffer? const remaining = this.buffer.length - this.currentIndex; if (this.currentIndex + newBuffer.length > this.buffer.length) { console.error( `Not enough space to write ${newBuffer.length}` + ` to this circular buffer with ${remaining} left.`); return; } this.buffer.set(newBuffer, this.currentIndex); this.currentIndex += newBuffer.length; } /** * How many samples are stored currently? */ getLength() { return this.currentIndex; } /** * How much space remains? */ getRemainingLength() { return this.buffer.length - this.currentIndex; } /** * Return the first N samples of the buffer, and remove them. Called when we * want to get a buffer of audio data of a fixed size. */ popBuffer(length: number) { // Do we have enough data to read back? if (this.currentIndex < length) { console.error( `This circular buffer doesn't have ${length} entries in it.`); return undefined; } if (length === 0) { console.warn(`Calling popBuffer(0) does nothing.`); return undefined; } const popped = this.buffer.slice(0, length); const remaining = this.buffer.slice(length, this.buffer.length); // Remove the popped entries from the buffer. this.buffer.fill(0); this.buffer.set(remaining, 0); // Send the currentIndex back. this.currentIndex -= length; return popped; } /** * Get the the first part of the buffer without mutating it. */ getBuffer(length?: number) { if (!length) { length = this.getLength(); } // Do we have enough data to read back? if (this.currentIndex < length) { console.error( `This circular buffer doesn't have ${length} entries in it.`); return undefined; } return this.buffer.slice(0, length); } clear() { this.currentIndex = 0; this.buffer.fill(0); } }
bevry/memo
source/test.ts
<filename>source/test.ts import { equal } from 'assert-helpers' import kava from 'kava' import memo from './index.js' let count = 0 function counter() { return ++count } kava.suite('memo', function (suite, test) { test('works as expected', function () { const fn = memo(counter) equal(count, 0) equal(fn(), 1) equal(count, 1) equal(fn(), 1) equal(count, 1) }) })
bevry/memo
source/index.ts
/** * Wraps the callback in a memo that reuses the first invocation result of the callback to avoid subsequent invocations. * @param callback The callback (that takes no arguments) that we wish to cache the result for. */ export default function memo<T>(callback: () => T): typeof callback { let value: T return () => (typeof value !== 'undefined' ? value : (value = callback())) }
coolreader18/legume-loader
src/when-dom-ready.ts
<gh_stars>1-10 const loadedStates = ["interactive", "complete"]; const whenDOMReady = (doc: Document) => new Promise(function(resolve) { if (loadedStates.indexOf(doc.readyState) !== -1) { resolve(); } else { doc.addEventListener("DOMContentLoaded", () => { resolve(); }); } }); export default whenDOMReady;
coolreader18/legume-loader
src/index.ts
<filename>src/index.ts import parseUrl, { LegumeUrl } from "./parse-url"; import * as parse from "./parse/parse"; import whenDOMReady from "./when-dom-ready"; const hasOwnProp = <O extends { [k in PropertyKey]: any }, K extends keyof O>( obj: O, key: K ): obj is O & { [k in K]-?: O[k] } => Object.prototype.hasOwnProperty.call(obj, key); interface LegumeOpts<R extends boolean | null | undefined = boolean | null> { /** The url to resolve relative requests from */ urlRef?: string | URL | LegumeUrl; /** * Whether or not to run the module. If true, always run it. If unset or null, * run it only if the exports aren't already cached. If false, never run it, * and return the url the request resolved to. */ run?: R; } /** * Load a module. * @param input - The legume url to load. * @param opts - Options for loading. * @returns a promise that resolves to the module's exports or its resolved url. */ async function Legume(input: string, opts?: LegumeOpts<false>): Promise<string>; async function Legume( input: string, opts?: LegumeOpts<true | null | undefined> ): Promise<any>; async function Legume(input: string, { urlRef, run = null }: LegumeOpts = {}) { const url = parseUrl(input, urlRef); const { href } = url.absUrl; if (hasOwnProp(Legume.cache, href)) { if (run == null) { return Legume.require(href); } else if (run) { return Legume.run(href); } else { return href; } } const { content, type } = await Legume.fetch(url); const id = url.absUrl.href; await Legume.load(content, { id, type, url }); if (run == null) { return Legume.require(id); } else if (run) { return Legume.run(id); } else { return url.absUrl.href; } } namespace Legume { export const version = "dev"; export const cache: { [id: string]: Module } = {}; interface LoadOpts { /** The id of the new module, what it's stored under in `Legume.cache` */ id: string; /** The media type of the new module */ type: MediaType; /** The url that the module was fetched from */ url?: LegumeUrl; /** The window that the module belongs to */ win?: Window; } /** * Load a module from its source text into the cache. * @param input - The source content of the module. * @param opts - Options and fields for loading. */ export async function load(input: string, { id, url, type, win }: LoadOpts) { let importsResult: parse.Parsed = { content: input, deps: [], hadImports: false }; switch (type) { case "script": importsResult = Legume.parseScript(input, { mapId: modId => parseUrl(modId, url).absUrl.href }); break; case "style": importsResult = Legume.parseStyle(input, { mapId: modId => parseUrl(modId, url).absUrl.href }); break; case "html": const parser = new DOMParser(); const dom = parser.parseFromString(input, "text/html"); dom .querySelectorAll("link[rel=stylesheet]") .forEach((link: HTMLLinkElement) => { link.href = parseUrl(link.getAttribute("href")!, url).absUrl.href; }); importsResult.content = dom.documentElement!.outerHTML; break; } const mod = new Module({ ...importsResult, type, id, url, win: win || window }); Legume.cache[id] = mod; if (mod.deps) { await Promise.all( mod.deps.map(dep => Legume(dep, { urlRef: url, run: false })) ); } } export interface ModuleInput { url?: LegumeUrl; content: string; deps: string[]; type: MediaType; id: string; hadImports: boolean; win: Window; } export class Module implements ModuleInput { constructor(mod: ModuleInput) { Object.assign(this, mod); } url?: LegumeUrl | undefined; content: string; deps: string[]; type: MediaType; id: string; win: Window; hasExports() { return hasOwnProp(this, "cjsExports") || hasOwnProp(this, "amdExports"); } get exports() { if (hasOwnProp(this, "amdExports")) { return this.amdExports; } if (hasOwnProp(this, "cjsExports")) { return this.cjsExports; } return this.setDefaultExports(); } set exports(exports: any) { this.cjsExports = exports; } cjsExports?: any; amdExports?: any; setDefaultExports() { let exports: any = undefined; switch (this.type) { case "script": case "html": exports = {}; if (this.type === "html" || this.hadImports) { Object.defineProperty(exports, "__esModule", { enumerable: false, value: true }); } break; } return (this.cjsExports = exports); } hadImports: boolean; loads: number = 0; define(...args: any[]) { const amdMod = amd.args(...args); amd.run(amdMod); if (hasOwnProp(amdMod, "exports")) { this.amdExports = amdMod.exports; } } getCJSModule(): CommonJSModule { const self = this; return { get exports() { return self.exports; }, set exports(exports: any) { self.exports = exports; }, legume: { get loads() { return self.loads; } }, require: (modId: string) => Legume.require(modId) }; } } interface CommonJSModule { exports: any; legume: { loads: number; }; require(modId: string): any; } const getMod = (modId: string): Module => { if (!hasOwnProp(Legume.cache, modId)) { throw new Error( `Module \`${modId}\` not loaded, call Legume.load() first` ); } return Legume.cache[modId]; }; export function require(modId: string): any { const mod = getMod(modId); if (mod.hasExports()) { return mod.exports; } return Legume.run(modId); } export function run(modId: string) { const mod = getMod(modId); const sourceURL = mod.url ? mod.url.absUrl || mod.url.request : `legume:${mod.id}`; switch (mod.type) { case "script": const code = `${mod.content}\n//# sourceURL=${sourceURL}`; const cjsMod = mod.getCJSModule(); const def = mod.define.bind(mod); def.amd = define.amd; const passedArgs = { module: cjsMod, exports: cjsMod.exports, require: cjsMod.require, Legume, define: def }; // @ts-ignore const modFunc = mod.win.Function.apply( undefined, Object.keys(passedArgs).concat(code) ); modFunc.apply( window, Object.keys(passedArgs).map(cur => passedArgs[cur]) ); return mod.exports; case "style": const elem = document.createElement("style"); elem.innerHTML = `${mod.content}\n/*# sourceUrl=${sourceURL} */`; if (mod.exports) { const prev = mod.exports as HTMLStyleElement; prev.parentNode!.replaceChild(elem, prev); } else { document.head!.appendChild(elem); } mod.exports = elem; return elem; case "html": const exports = mod.setDefaultExports(); interface OpenWindowOpts { height?: number; width?: number; } const openWindowBase = ( opts: OpenWindowOpts = {} ): [Window, Promise<void>] | null => { let optsString = ""; if (opts.height) optsString += `height=${opts.height},`; if (opts.width) optsString += `width=${opts.width},`; const win = window.open("", mod.id, optsString.slice(0, -1)); if (!win) return null; win.document.documentElement!.innerHTML = mod.content; // @ts-ignore win.Legume = Legume; const initProm = init({ doc: win.document, url: mod.url && mod.url.absUrl.href, win }) .then(() => whenDOMReady(win.document)) .then(() => {}); return [win, initProm]; }; const openWindow = (opts?: OpenWindowOpts): Window | null => { const res = openWindowBase(opts); return res && res[0]; }; exports["default"] = openWindow; exports.openWindowAsync = (opts): Promise<Window> => { const res = openWindowBase(opts); if (!res) return Promise.reject(res); return res[1].then(() => res[0]); }; return exports; } } export namespace amd { interface Module { factory: Function; deps?: string[]; id?: string; exports?: any; } export const cache: { [k: string]: Module } = {}; export const pending: { [k: string]: Module[] } = {}; export function args(...args: any[]): Module { let [arg0, arg1] = args; let id: string | undefined; let deps: string[] | undefined = []; let factory!: Function; const factoryArg = (arg: any) => { if (typeof arg === "object") { factory = () => arg; } else if (typeof arg === "function") { factory = arg; } else { throw new Error("Invalid define arguments"); } }; switch (args.length) { case 0: throw new Error("No args provided to define"); case 1: factoryArg(arg0); break; case 2: if (Array.isArray(arg0)) { deps = arg0; } else if (typeof arg0 === "string") { id = arg0; } else { throw new Error("Invalid define arguments"); } factoryArg(arg1); break; default: if (typeof arg0 !== "string" || !Array.isArray(arg1)) { throw new Error("Invalid define arguments"); } id = arg0; deps = arg1; factoryArg(args[2]); } return { factory, deps, id }; } export function run(mod: Module) { const deps = mod.deps || []; let isPending = deps.reduce((isPending, depId) => { if (!hasOwnProp(cache, depId)) { isPending = true; if (pending[depId]) { pending[depId].push(mod); } else { pending[depId] = [mod]; } } return isPending; }, false); if (!isPending) { const res = mod.factory(...deps.map(depId => getDep(depId, mod))); if (res) mod.exports = res; if (mod.id) { cache[mod.id] = mod; if (pending[mod.id]) { pending[mod.id].forEach(run); delete pending[mod.id]; } } } } export function getDep(depId: string, mod: Module) { if (depId === "exports") { return (mod.exports = {}); } else if (depId === "require") { return modId => getDep(modId, mod); } else if (depId === "module") { return { require: modId => getDep(modId, mod), get exports() { return mod.exports; }, set exports(exports) { mod.exports = exports; }, legume: { loads: 0 } }; } else { return cache[depId].exports; } } } export function define(...args: any[]) { amd.run(amd.args(...args)); } export namespace define { export const amd = {}; } export import parseScript = parse.parseScript; export import parseStyle = parse.parseStyle; type MediaType = "script" | "style" | "json" | "text" | "html" | "unknown"; interface FetchResult { type: MediaType; content: string; } const contentTypeToType: { [k: string]: MediaType } = { "application/json": "json", "application/javascript": "script", "text/css": "style", "text/html": "html" }; const extToType: { [k: string]: MediaType } = { js: "script", css: "style", json: "json", txt: "text", text: "text", html: "html", htm: "html" }; export async function fetch(url: LegumeUrl): Promise<FetchResult> { const res = await window.fetch(url.absUrl.href); let contentType = res.headers.get("Content-Type"); const content = await res.text(); let type!: MediaType; determineType: { if (contentType) { contentType = contentType.split(";")[0]; if (hasOwnProp(contentTypeToType, contentType)) { type = contentTypeToType[contentType]; break determineType; } } const match = url.request.pathname.match(/\.(.*)$/); if (match && hasOwnProp(extToType, match[1])) { type = extToType[match[1]]; break determineType; } console.warn(`Media type could not be determined for ${url.absUrl}`); type = "unknown"; } return { content, type }; } export async function init({ doc, entry, url, win }: { doc: Document; entry?: string | null; url?: string; win?: Window; }) { await whenDOMReady(doc); const scripts = Array.from( doc.querySelectorAll("script[type='text/legume']") ); if (entry) await Legume(entry, { urlRef: url }); for (const [script, i] of scripts.map( (cur, i): [Element, number] => [cur, i] )) { const processfn = async () => { const id = `inline-script-${i}`; // TODO: Figure out some way to show that it's an inline script and the document url await Legume.load(script.textContent || "", { id, type: "script", url: typeof url === "string" ? parseUrl(url) : undefined, win }); Legume.run(id); }; const prom = processfn().catch(console.error); if (script.getAttribute("async") === null) { await prom; } } } } declare const onLegumeDone: (() => void) | undefined; const curScript = document.currentScript; const entry = curScript && curScript.getAttribute("data-legume-entry"); Legume.init({ doc: document, entry }).then(() => { if (typeof onLegumeDone === "function") { onLegumeDone(); } }); export default Legume;
coolreader18/legume-loader
src/parse-url.ts
export interface LegumeUrl { absUrl: URL; request: URL; method: string; relative: boolean; } const parseUrl = (inUrl: string, ref?: string | URL | LegumeUrl): LegumeUrl => { let origUrl: URL; let relative = false; try { origUrl = new URL(inUrl); } catch (err) { origUrl = new URL( inUrl, ref ? ref instanceof URL || typeof ref === "string" ? ref : ref.absUrl : location.href ); relative = true; } const protocol = origUrl.protocol.slice(0, -1); let absUrl: URL; switch (protocol) { case "github": absUrl = new URL(`https://cdn.jsdelivr.net/gh/${origUrl.pathname}`); break; case "npm": absUrl = new URL(`https://cdn.jsdelivr.net/npm/${origUrl.pathname}`); break; case "gist": const split = origUrl.pathname.split("/"); const { hash } = origUrl; absUrl = new URL( hash ? `https://gistcdn.githack.com/${split .slice(0, 2) .join("/")}/raw/${hash.slice(1)}/${split[2]}` : `https://rawgist.now.sh/${split[1]}/${split[2]}` ); break; default: absUrl = origUrl; break; } return { absUrl, relative, request: origUrl, method: protocol }; }; export default parseUrl;
coolreader18/legume-loader
src/parse/common.ts
<filename>src/parse/common.ts<gh_stars>1-10 // string regex: /("(?:[^\r\n"]|\\"|\\\r?\n)*"|'(?:[^\r\n']|\\'|\\\r?\n)*')/; export const parseString = str => { str = str.replace(/\\\r?\n/g, ""); return JSON.parse( str[0] === "'" ? `"${str .replace(/"/g, '\\"') .replace(/\\'/g, "'") .slice(1, -2)}"` : str ); };
coolreader18/legume-loader
src/parse/parse-script.ts
import { Parsed, ParseOptions } from "./parse"; import { parseString } from "./common"; const identReg = /([a-zA-Z_$][a-zA-Z_$0-9]*)/.source; const buildRegex = (parts: Array<string | RegExp>, flags?: string) => RegExp( parts.map(cur => (cur instanceof RegExp ? cur.source : cur)).join(""), flags ); const nspImpComp = buildRegex([/\*\s*as\s+/, identReg]).source; const restReg = /\s*,?\s*((?:.|\r|\n)+)/; function reqDefault(obj) { return obj && obj.__esModule ? obj["default"] : obj; } function importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; } interface ImportStatement { defaultImport?: string; namedImports?: NamedImport[]; nspImport?: string; source: string; } /** * Parse a script into its imports and exports * @param script - The script text to parse */ export const parseScript = ( script: string, { mapId }: ParseOptions ): Parsed => { const reg = /(^|;|\*\/)?\s*(import)\s*\(|(^|;|\*\/)\s*import\s*((?:.|\r|\n)+?(?:"|'))(?=;|$)/gm; let hadImports = false; const deps: string[] = []; const content = script.replace(reg, (_, dyPrefix, dynamic, prefix, match) => { if (!dynamic) { hadImports = true; const cur: ImportStatement = { source: "" }; ident: { const ident = match.match(buildRegex(["^", identReg, restReg])); if (!ident) break ident; cur.defaultImport = ident[1]; match = ident[2]; } if (match[0] === "*") [cur.nspImport, match] = parseNamespace(match); else if (match[0] === "{") [cur.namedImports, match] = parseNamed(match); cur.source = parseEnd(match); deps.push(cur.source); if (mapId) cur.source = mapId(cur.source); return `${prefix}${transformDep(cur)}`; } else { /* * I hate it too, but otherwise: * func() * import("xxx") * would turn into * func()(function(){...})("xxx") */ return ` ${dyPrefix || ""}Array(function(id){return Legume(id).then(${importStar})})[0](`; } }); return { content, deps, hadImports }; }; const transformDep = (dep: ImportStatement) => { let out = "\n"; const src = JSON.stringify(dep.source); if (dep.defaultImport) { out += `;var ${dep.defaultImport}=(${reqDefault})(module.require(${src}));`; } if (dep.namedImports) { out += dep.namedImports .map( ({ imp, as }) => `;var ${as || imp}=module.require(${src})[${JSON.stringify(imp)}];` ) .join(""); } if (dep.nspImport) { const imp = dep.nspImport; out += `;var ${imp}=(${importStar})(module.require(${src}));`; } if (!dep.defaultImport && !dep.namedImports && !dep.nspImport) { out = `;module.require(${src});`; } return out; }; const parseNamespace = (str: string): [string, string] => { const nspMatch = str.match(buildRegex(["^", nspImpComp, restReg])); if (!nspMatch) throw new Error("Invalid namespace import statement"); return [nspMatch[1], nspMatch[2]]; }; interface NamedImport { imp: string; as?: string; } const parseNamed = (str: string): [NamedImport[], string] => { const initMatch = buildRegex(["{", restReg, "}", restReg]).exec(str); if (!initMatch) throw new Error("Invalid named parameters."); str = initMatch[1]; const reg = buildRegex( [identReg, "(?:\\s+as\\s+", identReg, ")?\\s*(?:,|$)"], "g" ); let match; const out: NamedImport[] = []; while ((match = reg.exec(str))) { const imp = match[1]; const as = match[2]; out.push(as ? { imp, as } : { imp }); } return [out, initMatch[2]]; }; const parseEnd = (str: string): string => { const srcMatch = str.match( /(?:from)?\s*("(?:[^\r\n"]|\\"|\\\r?\n)*"|'(?:[^\r\n']|\\'|\\\r?\n)*')/ ); if (!srcMatch) throw new Error("Invalid end of import statement"); return parseString(srcMatch[1]); };
coolreader18/legume-loader
common/bookmarklet.ts
export const makeUrl = (script: string, legumeVer?: string) => `javascript:(function(t,l,d,s,n){\ typeof Legume==n+""?(\ s=d.createElement("script"),\ s.src=l,s.setAttribute("data-legume-entry",t),\ d.head.appendChild(s)\ ):\ Legume(t,{run:true})\ })(${JSON.stringify(script)},${JSON.stringify( `https://cdn.jsdelivr.net/npm/legume-loader@${legumeVer || "latest"}` )},document);`;
coolreader18/legume-loader
src/parse/parse.ts
export interface Parsed { content: string; deps: string[]; hadImports: boolean; } export { parseScript } from "./parse-script"; export { parseStyle } from "./parse-style"; export interface ParseOptions { mapId: (modId: string) => string; }
coolreader18/legume-loader
src/parse/parse-style.ts
<reponame>coolreader18/legume-loader import { ParseOptions, Parsed } from "./parse"; import { parseString } from "./common"; export const parseStyle = (input: string, { mapId }: ParseOptions): Parsed => ({ content: input.replace( /\burl\((?:("(?:[^\r\n"]|\\"|\\\r?\n)*"|'(?:[^\r\n']|\\'|\\\r?\n)*')|([^\)"']+))\)/g, (_, quoted, noQuotes) => `url(${JSON.stringify(mapId(noQuotes || parseString(quoted)))})` ), deps: [], hadImports: false });
zzm2q/WOZLLA.js
src/assets/proxy/AssetProxy.ts
module WOZLLA.assets.proxy { export class AssetProxy { protected proxyTarget:IProxyTarget; protected asset:Asset; protected newAssetSrc:string; protected loading:boolean = false; constructor(proxyTarget:IProxyTarget) { this.proxyTarget = proxyTarget; } setAssetSrc(src:string) { this.newAssetSrc = src; } loadAsset(callback:Function) { if(this.checkDirty()) { if(this.loading) { callback && callback(); return; } this.loading = true; this.asset && this.asset.release(); this.asset = null; this.doLoad((asset:Asset) => { if(!asset) { this.asset = null; callback && callback(); } else if(asset.src !== this.newAssetSrc) { asset.retain(); asset.release(); this.asset = null; } else { this.asset = asset; this.asset.retain(); } this.loading = false; this.proxyTarget.onAssetLoaded(asset); callback && callback(); }); } else { callback && callback(); } } onDestroy() { this.asset && this.asset.release(); this.asset = null; } protected checkDirty():boolean { if(!this.asset) { return !!this.newAssetSrc; } return this.newAssetSrc !== this.asset.src; } protected doLoad(callback:(asset:Asset) => void) { callback(null); } } export interface IProxyTarget { onAssetLoaded(asset:Asset); } }
zzm2q/WOZLLA.js
src/renderer/internal/ShaderProgram.ts
<reponame>zzm2q/WOZLLA.js module WOZLLA.renderer { /** * @class WOZLLA.renderer.ShaderProgram * @extends WOZLLA.renderer.IShaderProgram */ export class ShaderProgram implements IShaderProgram { get id():any { return this._id ; } get vertexShader():any { return this._vertexShader; } get fragmentShader():any { return this._fragmentShader; } _id; _vertexShader; _fragmentShader; constructor(id, vertexShader, fragmentShader) { this._id = id; this._vertexShader = vertexShader; this._fragmentShader = fragmentShader; } useProgram(gl):void { gl.useProgram(this._id); } syncUniforms(gl, uniforms:{projection}) { } } }
zzm2q/WOZLLA.js
src/core/CoreEvent.ts
/// <reference path="../event/Event.ts"/> module WOZLLA { /** * internal class * @class WOZLLA.CoreEvent * @extends WOZLLA.event.Event */ export class CoreEvent extends WOZLLA.event.Event { /** * new a CoreEvent * @method constructor * @param type * @param bubbles * @param data * @param canStopBubbles */ constructor(type:string, bubbles:boolean=false, data:any=null, canStopBubbles:boolean=true) { super(type, bubbles, data, canStopBubbles); } } }
zzm2q/WOZLLA.js
src/renderer/ITextureDescriptor.ts
module WOZLLA.renderer { /** * @enum WOZLLA.renderer.TextureFormat */ export enum TextureFormat { /** @property {number} [PNG] */ PNG, /** @property {number} [JPEG] */ JPEG, /** @property {number} [PVR] */ PVR, } /** * @enum WOZLLA.renderer.PixelFormat */ export enum PixelFormat { /** @property {number} [RPGA8888] */ RGBA8888, /** @property {number} [RGBA4444] */ RGBA4444, /** @property {number} [RGB888] */ RGB888, /** @property {number} [RGB565] */ RGB565, /** @property {number} [PVRTC4] */ PVRTC4, /** @property {number} [PVRTC2] */ PVRTC2 } /** * @class WOZLLA.renderer.ITextureDescriptor * @abstract */ export interface ITextureDescriptor { width:number; height:number; textureFormat:TextureFormat; pixelFormat:PixelFormat; source:any; } }
zzm2q/WOZLLA.js
src/renderer/ITextureManager.ts
<gh_stars>0 module WOZLLA.renderer { /** * @class WOZLLA.renderer.ITextureManager * @abstract */ export interface ITextureManager { generateTexture(descriptor:ITextureDescriptor):ITexture; updateTexture(texture:ITexture):void; deleteTexture(texture:ITexture):void; getTexture(id):ITexture; clear():void; } export module ITextureManager { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.ITextureManager */ export var DOC = 'DOC'; } }
zzm2q/WOZLLA.js
src/math/Circle.ts
module WOZLLA.math { /** * @class WOZLLA.math.Circle * a util class for circle */ export class Circle { centerX:number; centerY:number; radius:number; constructor(centerX:number, centerY:number, radius:number) { /** * get or set centerX * @property {number} centerX */ this.centerX = centerX; /** * get or set centerY * @property {number} centerY */ this.centerY = centerY; /** * get or set radius * @property {number} radius */ this.radius = radius; } /** * @method containsXY * @param x * @param y * @returns {boolean} */ containsXY(x:number, y:number):boolean { return Math.pow((x - this.centerX), 2) + Math.pow((y - this.centerY), 2) <= this.radius; } /** * get simple description of this object * @returns {string} */ toString() { return 'Circle[' + this.centerX + ',' + this.centerY + ',' + this.radius + ']'; } } }
zzm2q/WOZLLA.js
src/renderer/IShaderProgram.ts
<reponame>zzm2q/WOZLLA.js<filename>src/renderer/IShaderProgram.ts<gh_stars>0 module WOZLLA.renderer { /** * @class WOZLLA.renderer.IShaderProgram * @abstract */ export interface IShaderProgram { id:any; vertexShader:any; fragmentShader:any; useProgram(gl):void; syncUniforms(gl, uniforms:{projection}); } export module IShaderProgram { /** * @property {string} V2T2C1A1 * @readonly * @static * @member WOZLLA.renderer.IShaderProgram */ export var V2T2C1A1 = 'Builtin_V2T2C1A1'; } }
zzm2q/WOZLLA.js
extensions/PureMVC/view/ListAdapter.ts
<filename>extensions/PureMVC/view/ListAdapter.ts ///<reference path='Adapter.ts'/> ///<reference path='AdapterFactory.ts'/> ///<reference path='../view/SimpleView.ts'/> ///<reference path='../model/ArrayStore.ts'/> ///<reference path='../../../src/utils/Assert.ts'/> module WOZLLA.PureMVC { var Assert = WOZLLA.Assert; export class ListAdapter extends Adapter { get arrayStore():ArrayStore<Model> { return <ArrayStore<Model>> this._adapterView.store; } get listView():ListView { return <ListView>this._adapterView; } getCount():number { var arrayStore:ArrayStore<Model> = this.arrayStore; return arrayStore ? arrayStore.count : 0; } getItem(index:any):Model { var arrayStore:ArrayStore<Model> = this.arrayStore; return arrayStore ? arrayStore.getAt(index) : null; } getView(index:any, callback:(view:SimpleView) => void) { this.loadItemView(index, callback); } onStoreBind(store:Store, callback:Function) { var loadedCount; var arrayStore = <ArrayStore<Model>>store; Assert.isTrue(store instanceof ArrayStore, 'ListAdapter only support bind ArrayStore'); arrayStore.addListenerScope('add', this.onStoreAdd, this); arrayStore.addListenerScope('remove', this.onStoreRemove, this); arrayStore.addListenerScope('clear', this.onStoreClear, this); arrayStore.addListenerScope('sync', this.onStoreSync, this); if(arrayStore.count === 0) { callback && callback(); } else { loadedCount = arrayStore.count; arrayStore.each((model:Model, idx:number) => { this.getView(idx, (itemView:SimpleView) => { this.listView.addItemView(itemView); if (--loadedCount === 0) { callback && callback(); } }); }); } } onStoreUnbind(store:Store) { var arrayStore = this.arrayStore; arrayStore.removeListenerScope('add', this.onStoreAdd, this); arrayStore.removeListenerScope('remove', this.onStoreRemove, this); arrayStore.removeListenerScope('clear', this.onStoreClear, this); arrayStore.removeListenerScope('sync', this.onStoreSync, this); this.listView.clearItemViews(); } onStoreAdd(e) { this.getView(e.data.index, (itemView) => { this.listView.addItemView(itemView); itemView.gameObject.loadAssets(() => itemView.gameObject.init()); }); } onStoreRemove(e) { this.listView.removeItemViewAt(e.data.index); } onStoreClear(e) { this.listView.clearItemViews(); } onStoreSync(e) { } protected loadItemView(index:any, callback?:(view:SimpleView) => void) { var viewBuilder = new ViewBuilder(); viewBuilder.setSync(); viewBuilder.instantiateWithSrc(this.listView.itemViewSrc); viewBuilder.addModel(ListView.DEFAUL_ITEM_MODEL_KEY, this.getItem(index)); viewBuilder.build((error:any, root:WOZLLA.GameObject) => { var itemView = <SimpleView>root.getComponent(SimpleView); callback && callback(itemView); }); } } AdapterFactory.register('ListAdapter', ListAdapter); }
zzm2q/WOZLLA.js
src/renderer/internal/Texture.ts
<gh_stars>0 module WOZLLA.renderer { /** * @class WOZLLA.renderer.Texture * @extends WOZLLA.renderer.ITexture */ export class Texture implements ITexture { get id():any { return this._id; } get descriptor():ITextureDescriptor { return this._descriptor; } _id:any; _descriptor:ITextureDescriptor; constructor(id, descriptor:ITextureDescriptor) { this._id = id; this._descriptor = descriptor; } bind(gl) { gl.bindTexture(gl.TEXTURE_2D, this._id); } } }
zzm2q/WOZLLA.js
extensions/PureMVC/view/AdapterFactory.ts
module WOZLLA.PureMVC { export class AdapterFactory { private static adapterCtorMap:any = {}; public static create(name:string) { var AdapterClass:any = AdapterFactory.adapterCtorMap[name]; Assert.isNotUndefined(AdapterClass, 'unknow adapter: ' + name); return new AdapterClass(); } public static register(name:string, AdapterClass:Function) { Assert.isUndefined(AdapterFactory.adapterCtorMap[name], 'adapter name="' + name + '" has been registered'); AdapterFactory.adapterCtorMap[name] = AdapterClass; } } }
zzm2q/WOZLLA.js
extensions/PureMVC/model/ArrayStore.ts
///<reference path='../../../libs/puremvc-typescript-multicore-1.1.d.ts'/> ///<reference path='Model.ts'/> ///<reference path='Store.ts'/> module WOZLLA.PureMVC { export class ArrayStore<T extends Model> extends Store { protected list = []; get count():number { return this.list.length; } add(model:T, silent:boolean=false) { this.addAt(model, this.list.length, silent); } addAt(model:T, index:number, silent:boolean=false) { this.list.splice(index, 0, model); if(!silent) { this.dispatchEvent(new WOZLLA.event.Event('add', true, new ArrayStoreEventData(model, index))); } } remove(model:T, silent:boolean=false) { var index = this.indexOf(model); if(index !== -1) { this.removeAt(index, silent); } } removeAt(index:number, silent:boolean=false) { var model = this.list[index]; this.list.splice(index, 1); if(!silent) { this.dispatchEvent(new WOZLLA.event.Event('remove', true, new ArrayStoreEventData(model, index))); } } clear(silent:boolean=false) { this.list.length = 0; if(!silent) { this.dispatchEvent(new WOZLLA.event.Event('clear', true)); } } getAt(index:number) { return this.list[index]; } getRange(start:number, count:number):Array<T> { return this.list.slice(start, start+count); } indexOf(model:T) { return this.list.indexOf(model); } sync() { this.dispatchEvent(new WOZLLA.event.Event('sync', true)); } each(func:(model:T, index:number) => any) { var list = this.list.slice(0); list.forEach(func); } query(func:(model:T, index:number) => any):Array<T> { var result = []; this.each((model:T, index:number) => { if(func(model, index)) { result.push(model); } }); return result; } sort(func:(a:T, b:T) => any, silent:boolean=false) { this.list.sort(func); if(!silent) { this.dispatchEvent(new WOZLLA.event.Event('sort', true)); } } } export class ArrayStoreEventData { constructor(public model:Model, public index:number) { } } }
zzm2q/WOZLLA.js
extensions/DragonBones/WSlot.ts
<filename>extensions/DragonBones/WSlot.ts /// <reference path="../../libs/DragonBones.d.ts"/> /// <reference path="../../src/core/GameObject.ts"/> module WOZLLA.DragonBones { export class WSlot extends dragonBones.Slot { private _display:WOZLLA.GameObject; constructor() { super(this); this._display = null; } public dispose():void{ if(this._display) { this._display.destroy(); this._display.removeMe(); } super.dispose(); this._display = null; } /** @private */ public _updateDisplay(value:any):void{ this._display = <WOZLLA.GameObject>value; } //Abstract method /** @private */ public _getDisplayIndex():number { return -1; } /** @private */ public _addDisplayToContainer(container:any, index:number=-1):void{ var gameObjContainer = <WOZLLA.GameObject> container; if(this._display && gameObjContainer) { gameObjContainer.addChild(this._display); } } /** @private */ public _removeDisplayFromContainer():void{ if(this._display && this._display.parent) { this._display.parent.removeChild(this._display); } } /** @private */ public _updateTransform():void { var trans; if(this._display) { trans = this._display.transform; trans.__local_matrix = this._globalTransformMatrix; trans.dirty = true; //trans.setPosition(this._global.x, this._global.y); //trans.setScale(this._global.scaleX, this._global.scaleY); //trans.setSkew(this._global.skewX, this._global.skewY); //trans.setRotation(this._global.rotation); } } /** @private */ public _updateDisplayVisible(value:boolean):void{ if(this._display && this._parent) { this._display.visible = this._parent._visible && this._visible && value; } } /** @private */ public _updateDisplayColor(aOffset:number, rOffset:number, gOffset:number, bOffset:number, aMultiplier:number, rMultiplier:number, gMultiplier:number, bMultiplier:number):void { super._updateDisplayColor(aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier); if(this._display) { var spriteRenderer:WOZLLA.component.SpriteRenderer = <WOZLLA.component.SpriteRenderer>this._display.renderer; if(spriteRenderer) { spriteRenderer.alpha = aMultiplier; } // TODO color } } /** @private */ public _updateDisplayBlendMode(value:string):void{ if(this._display && value) { } } } }
zzm2q/WOZLLA.js
src/layout/VBox.ts
/// <reference path="LayoutBase.ts"/> /// <reference path="../component/PropertyConverter.ts"/> module WOZLLA.layout { export class VBox extends LayoutBase { get padding():Padding { return this._padding; } set padding(padding:Padding) { if(this._padding && this._padding.equals(padding)) return; this._padding = padding; this.requestLayout(); } get itemMargin():number { return this._itemMargin; } set itemMargin(margin:number) { if(this._itemMargin === margin) return; this._itemMargin = margin; this.requestLayout(); } _padding:Padding; _itemMargin:number; doLayout():void { var padding = this._padding; var y = padding.top; this.gameObject.eachChild((child:GameObject, idx:number) => { var rectTransform = child.rectTransform; if(!rectTransform) { child.transform.x = padding.left; child.transform.y = y; } else { rectTransform.anchorMode = RectTransform.ANCHOR_LEFT | RectTransform.ANCHOR_TOP; rectTransform.px = padding.left; rectTransform.py = y; } y += this._itemMargin + this.measureChildHeight(child, idx); }); } protected measureChildHeight(child:GameObject, idx:number):number { var rectTransform = child.rectTransform; if(!rectTransform) { return 0; } else { return rectTransform.height; } } } Component.register(VBox, { name: 'VBox', properties: [{ name: 'padding', type: 'Padding', convert: component.PropertyConverter.array2Padding, defaultValue: [0, 0, 0, 0] }, { name: 'itemMargin', type: 'int', defaultValue: 0 }] }); }
zzm2q/WOZLLA.js
extensions/DragonBones/WTextureAtlas.ts
/// <reference path="../../libs/DragonBones.d.ts"/> /// <reference path="../../src/assets/SpriteAtlas.ts"/> module WOZLLA.DragonBones { function getFileName(url) { var idx = url.lastIndexOf('/'); if(idx !== -1) { return url.substr(idx+1, url.length); } return url; } export class WTextureAtlas extends WOZLLA.assets.SpriteAtlas implements dragonBones.ITextureAtlas { public name:string; public dispose():void {} public getRegion(subTextureName:string):dragonBones.Rectangle { var sprite = this.getSprite(subTextureName); var frame = sprite.frame; return new dragonBones.Rectangle(frame.x, frame.y, frame.width, frame.height); } _loadSpriteAtlas(callback:(error:string, image?, spriteData?)=>any) { WOZLLA.utils.Ajax.request({ url: this._metaSrc, contentType: 'json', success: (data:any) => { var imageSuffix = data.imagePath; var metaFileName = getFileName(this._metaSrc); this._imageSrc = this._metaSrc.replace(new RegExp(metaFileName + '$'), imageSuffix); this._loadImage((error, image) => { if(error) { callback && callback(error); } else { var textureData = this._parseData(data); this.name = textureData.name; callback && callback(null, image, textureData); } }); }, error : (err) => { callback('Fail to load sprite: ' + this._metaSrc + ', ' + err.code + ':' + err.message); } }); } _parseData(data:any):any { var spriteData = { name: data.name, frames: {} }; data.SubTexture.forEach(function(frameData) { spriteData.frames[frameData.name] = { frame: frameData }; }); return spriteData; } } }
zzm2q/WOZLLA.js
src/core/Scheduler.ts
<filename>src/core/Scheduler.ts /// <reference path="Time.ts"/> module WOZLLA { /** * @class WOZLLA.Scheduler * @singleton */ export class Scheduler { private static instance; /** * @method {WOZLLA.Scheduler} getInstance * @static * @member WOZLLA.Scheduler */ public static getInstance() { if(!Scheduler.instance) { Scheduler.instance = new Scheduler(); } return Scheduler.instance; } private _scheduleCount = 0; private _lastSchedules; private _schedules:any = {}; runSchedule() { var scheduleId, scheduleItem, schedules; var markScheduleCount = this._scheduleCount; if(this._lastSchedules) { for(scheduleId in this._schedules) { this._lastSchedules[scheduleId] = this._schedules[scheduleId]; } } else { this._lastSchedules = this._schedules; } this._schedules = {}; schedules = this._lastSchedules; for(scheduleId in schedules) { scheduleItem = schedules[scheduleId]; if(scheduleItem.isFrame && !scheduleItem.paused) { scheduleItem.frame --; if(scheduleItem.frame < 0) { delete schedules[scheduleId]; scheduleItem.task.apply(scheduleItem, scheduleItem.args); } } else if(scheduleItem.isTime && !scheduleItem.paused) { scheduleItem.time -= Time.delta; if(scheduleItem.time < 0) { delete schedules[scheduleId]; scheduleItem.task.apply(scheduleItem, scheduleItem.args); } } else if(scheduleItem.isInterval && !scheduleItem.paused) { scheduleItem.time -= Time.delta; if(scheduleItem.time < 0) { scheduleItem.task.apply(scheduleItem, scheduleItem.args); scheduleItem.time += scheduleItem.intervalTime; } } else if(scheduleItem.isLoop && !scheduleItem.paused) { scheduleItem.task.apply(scheduleItem, scheduleItem.args); } } if(markScheduleCount < this._scheduleCount) { this.runSchedule(); } } /** * remove the specify schedule by id * @param id */ removeSchedule(id) { delete this._schedules[id]; } /** * schedule the task to each frame * @param task * @param args * @returns {string} schedule id */ scheduleLoop(task, args?) { var scheduleId = 'Schedule_' + (this._scheduleCount++); this._schedules[scheduleId] = { task : task, args : args, isLoop : true }; return scheduleId; } /** * schedule the task to the next speficied frame * @param task * @param {number} frame * @param args * @returns {string} schedule id */ scheduleFrame(task, frame=0, args?) { var scheduleId = 'Schedule_' + (this._scheduleCount++); this._schedules[scheduleId] = { task : task, frame : frame, args : args, isFrame : true }; return scheduleId } /** * schedule the task to internal, like setInterval * @param task * @param time * @param args * @returns {string} schedule id */ scheduleInterval(task, time=0, args?) { var scheduleId = 'Schedule_' + (this._scheduleCount++); this._schedules[scheduleId] = { task : task, intervalTime : time, time : time, args : args, isInterval : true }; return scheduleId } /** * schedule the task to time, like setTimeout * @param task * @param time * @param args * @returns {string} schedule id */ scheduleTime(task, time=0, args?) { var scheduleId = 'Schedule_' + (this._scheduleCount++); time = time || 0; this._schedules[scheduleId] = { task : task, time : time, args : args, isTime : true }; return scheduleId; } /** * resume the specified schedule * @param scheduleId */ resumeSchedule(scheduleId) { this._schedules[scheduleId].paused = false; } /** * pause the specified schedule * @param scheduleId */ pauseSchedule(scheduleId) { this._schedules[scheduleId].paused = true; } } }
zzm2q/WOZLLA.js
src/renderer/ILayerManager.ts
module WOZLLA.renderer { /** * @class WOZLLA.renderer.ILayerManager * @abstract */ export interface ILayerManager { define(layer:string, zindex:number):void; undefine(layer:string):void; getZIndex(layer:string):number; getSortedLayers():Array<string>; } export module ILayerManager { /** * @property {string} DEFAULT * @readonly * @static * @member WOZLLA.renderer.ILayerManager */ export var DEFAULT = 'default'; } }
zzm2q/WOZLLA.js
src/core/Renderer.ts
<filename>src/core/Renderer.ts module WOZLLA { /** * Abstract base class for Renderer component * @class WOZLLA.Renderer * @abstract */ export class Renderer extends Component { /** * render this object * @param renderer * @param flags */ render(renderer:WOZLLA.renderer.IRenderer, flags:number):void {} } }
zzm2q/WOZLLA.js
src/component/collider/MaskCollider.ts
/// <reference path="../../core/Collider.ts"/> /// <reference path="../../math/Rectangle.ts"/> module WOZLLA.component { /** * @class WOZLLA.component.MaskCollider */ export class MaskCollider extends WOZLLA.Collider { collideXY(localX:number, localY:number):boolean { return true; } collide(collider:Collider):boolean { return false; } } }
zzm2q/WOZLLA.js
src/renderer/WebGLExtension.ts
module WOZLLA.renderer { /** * @class WOZLLA.renderer.WebGLExtension */ export class WebGLExtension { public static VENDOR_WEBKIT = 'WEBKIT_'; public static PVRTC = 'WEBGL_compressed_texture_pvrtc'; public static COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02; public static COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03; public static getExtension(gl, extName, doThrow:boolean=true):any { var ext = gl.getExtension(extName) || gl.getExtension(gl, WebGLExtension.VENDOR_WEBKIT + extName); if(ext != null) { return ext; } else if(doThrow) { throw new Error('Unsupported extension: ' + extName); } } } }
zzm2q/WOZLLA.js
src/renderer/shader/V2T2C1A1.ts
<reponame>zzm2q/WOZLLA.js<filename>src/renderer/shader/V2T2C1A1.ts module WOZLLA.renderer.shader { /** * @class WOZLLA.renderer.shader.V2T2C1A1 */ export class V2T2C1A1 extends WOZLLA.renderer.ShaderProgram implements IShaderProgram { public static VERTEX_SOURCE:string = [ 'attribute vec2 aVertexPosition;\n', 'attribute vec2 aTextureCoord;\n', 'attribute vec2 aColor;\n', 'uniform vec2 projectionVector;\n', 'uniform vec2 offsetVector;\n', 'varying vec2 vTextureCoord;\n', 'varying vec4 vColor;\n', 'const vec2 center = vec2(-1.0, 1.0);\n', 'void main(void) {\n', 'gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);\n', 'vTextureCoord = aTextureCoord;\n', 'vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;\n', 'vColor = vec4(color * aColor.x, aColor.x);\n', '}' ].join(''); public static FRAGMENT_SOURCE:string = [ 'precision mediump float;\n', 'varying vec2 vTextureCoord;\n', 'varying vec4 vColor;\n', 'uniform sampler2D uSampler;\n', 'void main(void) {\n', 'gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;\n', '}' ].join(''); _locations:any = { initialized: false }; constructor(id, vertexShader, fragmentShader) { super(id, vertexShader, fragmentShader); } useProgram(gl):void { super.useProgram(gl); if(!this._locations.initialized) { this._initLocaitions(gl); this._locations.initialized = true; } this._activate(gl); } syncUniforms(gl, uniforms:{projection}) { gl.uniform2f(this._locations.projectionVector, uniforms.projection.x, uniforms.projection.y); } _initLocaitions(gl) { var program = this._id; this._locations.uSampler = gl.getUniformLocation(program, 'uSampler'); this._locations.projectionVector = gl.getUniformLocation(program, 'projectionVector'); this._locations.offsetVector = gl.getUniformLocation(program, 'offsetVector'); this._locations.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); this._locations.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); this._locations.aColor = gl.getAttribLocation(program, 'aColor'); } _activate(gl) { gl.activeTexture(gl.TEXTURE0); var stride = Quad.V2T2C1A1.strade * 4; gl.vertexAttribPointer(this._locations.aVertexPosition, 2, gl.FLOAT, false, stride, 0); gl.vertexAttribPointer(this._locations.aTextureCoord, 2, gl.FLOAT, false, stride, 2 * 4); gl.vertexAttribPointer(this._locations.aColor, 2, gl.FLOAT, false, stride, 4 * 4); gl.enableVertexAttribArray(this._locations.aVertexPosition); gl.enableVertexAttribArray(this._locations.aTextureCoord); gl.enableVertexAttribArray(this._locations.aColor); } } }
zzm2q/WOZLLA.js
extensions/PureMVC/model/Store.ts
<reponame>zzm2q/WOZLLA.js<filename>extensions/PureMVC/model/Store.ts ///<reference path='../../../libs/puremvc-typescript-multicore-1.1.d.ts'/> ///<reference path='../../../src/event/EventDispatcher.ts' /> module WOZLLA.PureMVC { export class Store extends WOZLLA.event.EventDispatcher { } }
zzm2q/WOZLLA.js
src/core/RectTransform.ts
/// <reference path="Transform.ts"/> module WOZLLA { /** * RectTransform is a subclass of {@link WOZLLA.Transform}, define a rect region * for {@WOZLLA.GameObject} and a anchor mode to specify how to related to it's parent. * @class WOZLLA.RectTransform */ export class RectTransform extends Transform { public static getMode(name):number { var names = name.split('_'); var value = 0; switch(names[0]) { case 'Left': value |= RectTransform.ANCHOR_LEFT; break; case 'Right': value |= RectTransform.ANCHOR_RIGHT; break; case 'HStrength': value |= RectTransform.ANCHOR_HORIZONTAL_STRENGTH; break; default: value |= RectTransform.ANCHOR_CENTER; break; } switch(names[1]) { case 'Top': value |= RectTransform.ANCHOR_TOP; break; case 'Bottom': value |= RectTransform.ANCHOR_BOTTOM; break; case 'VStrength': value |= RectTransform.ANCHOR_VERTICAL_STRENGTH; break; default: value |= RectTransform.ANCHOR_MIDDLE; break; } return value; } /** * vertical anchor mode * @property {number} ANCHOR_TOP * @readonly * @static */ public static ANCHOR_TOP = 0x1; /** * vertical anchor mode * @property {number} ANCHOR_MIDDLE * @readonly * @static */ public static ANCHOR_MIDDLE = 0x10; /** * vertical anchor mode * @property {number} ANCHOR_BOTTOM * @readonly * @static */ public static ANCHOR_BOTTOM = 0x100; /** * vertical anchor mode * @property {number} ANCHOR_VERTICAL_STRENGTH * @readonly * @static */ public static ANCHOR_VERTICAL_STRENGTH = 0x1000; /** * horizontal anchor mode * @property {number} ANCHOR_LEFT * @readonly * @static */ public static ANCHOR_LEFT = 0x10000; /** * horizontal anchor mode * @property {number} ANCHOR_CENTER * @readonly * @static */ public static ANCHOR_CENTER = 0x100000; /** * horizontal anchor mode * @property {number} ANCHOR_RIGHT * @readonly * @static */ public static ANCHOR_RIGHT = 0x1000000; /** * horizontal anchor mode * @property {number} ANCHOR_HORIZONTAL_STRENGTH * @readonly * @static */ public static ANCHOR_HORIZONTAL_STRENGTH = 0x10000000; /** * get or set width, this property only effect on fixed size mode * @property {number} width */ get width():number { return this._width; } set width(value:number) { if(this._width === value) return; this._width = value; this.dirty = true; } /** * get or set height, this property only effect on fixed size mode * @property {number} height */ get height():number { return this._height; } set height(value:number) { if(this._height === value) return; this._height = value; this.dirty = true; } /** * get or set top * @property {number} top */ get top():number { return this._top; } set top(value:number) { if(this._top === value) return; this._top = value; this.dirty = true; } /** * get or set left * @property {number} left */ get left():number { return this._left; } set left(value:number) { if(this._left === value) return; this._left = value; this.dirty = true; } /** * get or set right * @property {number} right */ get right():number { return this._right; } set right(value:number) { if(this._right === value) return; this._right = value; this.dirty = true; } /** * get or set bottom * @property {number} bottom */ get bottom():number { return this._bottom; } set bottom(value:number) { if(this._bottom === value) return; this._bottom = value; this.dirty = true; } /** * get or set px, this only effect on strengthen mode * @property {number} px specify x coords */ get px():number { return this._px; } set px(value:number) { if(this._px === value) return; this._px = value; this.dirty = true; } /** * get or set py, this only effect on strengthen mode * @property {number} py specify y coords */ get py():number { return this._py; } set py(value:number) { if(this._py === value) return; this._py = value; this.dirty = true; } /** * get or set anchor mode * @property {number} anchorMode */ get anchorMode():number { return this._anchorMode; } set anchorMode(value:number) { if(this._anchorMode === value) return; this._anchorMode = value; this.dirty = true; } _width:number = 0; _height:number = 0; _top:number = 0; _left:number = 0; _right:number = 0; _bottom:number = 0; _px:number = 0; _py:number = 0; _anchorMode = RectTransform.ANCHOR_CENTER | RectTransform.ANCHOR_MIDDLE; /** * set rect transform * @param {WOZLLA.RectTransform} rectTransform */ set(rectTransform:RectTransform) { var anchorMode:any = rectTransform.anchorMode; if(typeof anchorMode === 'string') { anchorMode = RectTransform.getMode(anchorMode); } this._anchorMode = anchorMode; this._width = rectTransform.width || 0; this._height = rectTransform.height || 0; this._top = rectTransform.top || 0; this._left = rectTransform.left || 0; this._right = rectTransform.right || 0; this._bottom = rectTransform.bottom || 0; this._px = rectTransform.px || 0; this._px = rectTransform.py || 0; this.dirty = true; } /** * transform with parent transform * @param {WOZLLA.Transform} parentTransform */ transform(parentTransform:Transform=null) { var m, R, p:RectTransform; if(!parentTransform || !this._relative || !(parentTransform instanceof RectTransform)) { p = Director.getInstance().viewRectTransform; } else { p = <RectTransform>parentTransform; } m = this._anchorMode; R = RectTransform; if((m & R.ANCHOR_LEFT) === R.ANCHOR_LEFT) { this.x = this._px; } else if((m & R.ANCHOR_RIGHT) === R.ANCHOR_RIGHT) { this.x = p._width + this._px; } else if((m & R.ANCHOR_HORIZONTAL_STRENGTH) === R.ANCHOR_HORIZONTAL_STRENGTH) { this.x = this._left; this._width = p._width - this._left - this._right; } else { this.x = p._width/2 + this._px; } if((m & R.ANCHOR_TOP) === R.ANCHOR_TOP) { this.y = this._py; } else if((m & R.ANCHOR_BOTTOM) === R.ANCHOR_BOTTOM) { this.y = p._height + this._py; } else if((m & R.ANCHOR_VERTICAL_STRENGTH) === R.ANCHOR_VERTICAL_STRENGTH) { this.y = this._top; this._height = p._height - this._top - this._bottom; } else { this.y = p._height/2 + this._py; } super.transform(parentTransform); } } }
zzm2q/WOZLLA.js
extensions/PureMVC/model/Model.ts
///<reference path='../../../libs/puremvc-typescript-multicore-1.1.d.ts'/> ///<reference path='../../../src/event/EventDispatcher.ts' /> module WOZLLA.PureMVC { var modelIdGen = 0; function generateModelId():string { return ++modelIdGen + ''; } export class Model extends WOZLLA.event.EventDispatcher { protected data:any = { _modelId: generateModelId() }; protected definedField:any = {}; constructor() { super(); this.initFields(); } initFields() { this.defineField('_modelId'); } defineField(field:string) { this.definedField[field] = true; } defineFields(array:Array<string>) { array.forEach((field:string) => { this.defineField(field); }); } get(field:string):any { Assert.isTrue(this.definedField[field], 'Field not defined: ' + field); return this.data[field]; } set(field:string, value:any, silent:boolean=false) { var oldValue; Assert.isTrue(this.definedField[field], 'Field not defined: ' + field); oldValue = this.data[field]; this.data[field] = value; if(!silent) { this.dispatchEvent(new WOZLLA.event.Event( 'fieldchanged', true, new FieldChangeEventData(field, value, oldValue))); } } setAll(data:any, silent:boolean=false) { for(var field in this.definedField) { if(data.hasOwnProperty(field)) { this.set(field, data[field], silent); } } } } export class FieldChangeEventData { get field():string { return this._field; } get value():any { return this._value; } get oldValue():any { return this._oldValue; } _field:string; _value:any; _oldValue:any; constructor(field:string, value:any, oldValue:any) { this._field = field; this._value = value; this._oldValue = oldValue; } } }
zzm2q/WOZLLA.js
src/core/Transform.ts
/// <reference path="../math/Matrix.ts"/> /// <reference path="../utils/Tween.ts"/> module WOZLLA { var helpMatrix = new WOZLLA.math.Matrix(); /** * this class define the position, scale, rotation and about transform information of {@link WOZLLA.GameObject} * @class WOZLLA.Transform */ export class Transform { // for dragonbone public __local_matrix:any; /** * @property {number} DEG_TO_RAD * @readonly * @static */ public static DEG_TO_RAD = Math.PI/180; /** * @property {WOZLLA.math.Matrix} worldMatrix * @readonly */ public worldMatrix:WOZLLA.math.Matrix = new WOZLLA.math.Matrix(); /** * specify this tranform * @type {boolean} */ public useGLCoords:boolean = false; _values:Array<number>; _relative:boolean = true; _dirty:boolean = false; constructor() { this._values = new Array<number>(9); this.reset(); } get x() { return this._values[0]; } set x(value:any) { this._values[0] = value; this._dirty = true; } get y() { return this._values[1]; } set y(value:any) { this._values[1] = value; this._dirty = true; } get rotation() { return this._values[4]; } set rotation(value:any) { this._values[4] = value; this._dirty = true; } get scaleX() { return this._values[5]; } set scaleX(value:any) { this._values[5] = value; this._dirty = true; } get scaleY() { return this._values[6]; } set scaleY(value:any) { this._values[6] = value; this._dirty = true; } get skewX() { return this._values[7]; } set skewX(value:any) { this._values[7] = value; this._dirty = true; } get skewY() { return this._values[8]; } set skewY(value:any) { this._values[8] = value; this._dirty = true; } get relative():boolean { return this._relative; } set relative(relative:boolean) { this._relative = relative; this._dirty = true; } get dirty() { return this._dirty; } set dirty(value:boolean) { this._dirty = value; } setPosition(x, y) { this._values[0] = x; this._values[1] = y; this._dirty = true; } setAnchor(anchorX, anchorY) { this._values[2] = anchorX; this._values[3] = anchorY; this._dirty = true; } setRotation(rotation) { this._values[4] = rotation; this._dirty = true; } setScale(scaleX, scaleY) { this._values[5] = scaleX; this._values[6] = scaleY; this._dirty = true; } setSkew(skewX, skewY) { this._values[7] = skewX; this._values[8] = skewY; this._dirty = true; } reset() { this._values[0] = 0; // x this._values[1] = 0; // y this._values[2] = 0; // @deprecated this._values[3] = 0; // @deprecated this._values[4] = 0; // rotation this._values[5] = 1; // scaleX this._values[6] = 1; // scaleY this._values[7] = 0; // skewX this._values[8] = 0; // skewY } set(transform:any) { if(typeof transform.x === "number") { this._values[0] = transform.x; //x } if(typeof transform.y === "number") { this._values[1] = transform.y; // y } if(typeof transform.rotation === 'number') { this._values[4] = transform.rotation; // rotation } if(typeof transform.scaleX === 'number') { this._values[5] = transform.scaleX; // scaleX } if(typeof transform.scaleY === 'number') { this._values[6] = transform.scaleY; // scaleY } if(typeof transform.skewX === 'number') { this._values[7] = transform.skewX; // skewX } if(typeof transform.skewY === 'number') { this._values[8] = transform.skewY; // skewY } if(typeof transform.relative !== 'undefined') { this._relative = transform.relative; } this._dirty = true; } transform(parentTransform:Transform=null) { var cos, sin, r; var matrix; var worldMatrix = this.worldMatrix; var x = this._values[0]; var y = this._values[1]; var rotation = this._values[4]; var scaleX = this._values[5]; var scaleY = this._values[6]; var skewX = this._values[7]; var skewY = this._values[8]; if(this.useGLCoords) { skewX += 180; } if(parentTransform && this._relative) { worldMatrix.applyMatrix(parentTransform.worldMatrix); } else { // worldMatrix.identity(); // parentTransform = Director.getInstance().getStage().transform; // if this is the transform of stage if(this === parentTransform) { worldMatrix.identity(); } else { worldMatrix.applyMatrix(parentTransform.worldMatrix); } } if(this.__local_matrix) { matrix = this.__local_matrix; worldMatrix.append(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); this._dirty = false; return; } if (rotation%360) { r = rotation*Transform.DEG_TO_RAD; cos = Math.cos(r); sin = Math.sin(r); } else { cos = 1; sin = 0; } if (skewX || skewY) { skewX *= Transform.DEG_TO_RAD; skewY *= Transform.DEG_TO_RAD; worldMatrix.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); worldMatrix.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); } else { worldMatrix.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); } this._dirty = false; } updateWorldMatrix() { if(!this._dirty) { return; } var matrix = this.worldMatrix; if (matrix) { matrix.identity(); } else { matrix = new WOZLLA.math.Matrix(); } var o:any = this; while (o != null) { matrix.prependTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, 0, 0); o = o.parent; } } globalToLocal(x, y, updateMatrix:boolean=false) { if(updateMatrix) { this.updateWorldMatrix(); } helpMatrix.applyMatrix(this.worldMatrix); helpMatrix.invert(); helpMatrix.append(1, 0, 0, 1, x, y); return { x : helpMatrix.values[6], y : helpMatrix.values[7] }; } localToGlobal(x, y, updateMatrix:boolean=false) { if(updateMatrix) { this.updateWorldMatrix(); } helpMatrix.applyMatrix(this.worldMatrix); helpMatrix.append(1, 0, 0, 1, x, y); return { x : helpMatrix.values[6], y : helpMatrix.values[7] }; } tween(override:boolean):any { return WOZLLA.utils.Tween.get(this, null, null, override); } clearTweens() { return WOZLLA.utils.Tween.removeTweens(this); } } }
zzm2q/WOZLLA.js
src/component/primitive/RectRenderer.ts
/// <reference path="PrimitiveRenderer.ts"/> module WOZLLA.component { export class RectRenderer extends PrimitiveRenderer { get rect():WOZLLA.math.Rectangle { return this._rect; } set rect(value:WOZLLA.math.Rectangle) { this._rect = value; this._graphicsDirty = true; } _rect:WOZLLA.math.Rectangle; drawPrimitive(context):void { var style = this._primitiveStyle; if(style.stroke) { context.rect(style.strokeWidth/2, style.strokeWidth/2, this._rect.width, this._rect.height); context.stroke(); } else { context.rect(0, 0, this._rect.width, this._rect.height); } if(style.fill) { context.fill(); } } protected measurePrimitiveSize():any { var style = this._primitiveStyle; if(!this._rect) { return { width: 0, height: 0 }; } return { width: Math.ceil(this._rect.width + (style.stroke ? style.strokeWidth : 0)), height: Math.ceil(this._rect.height + (style.stroke ? style.strokeWidth : 0)) }; } protected generateCanvasTexture(renderer:renderer.IRenderer):void { var offset = { x: -this._rect.x/this._rect.width, y: -this._rect.y/this._rect.height }; super.generateCanvasTexture(renderer); this.setTextureOffset(offset); } } }
zzm2q/WOZLLA.js
src/component/text/TextRenderer.ts
<filename>src/component/text/TextRenderer.ts<gh_stars>0 /// <reference path="../renderer/CanvasRenderer.ts"/> /// <reference path="../PropertyConverter.ts"/> module WOZLLA.component { var helpCanvas = document.createElement('canvas'); helpCanvas.width = 1; helpCanvas.height = 1; var helpContext = helpCanvas.getContext('2d'); export class TextRenderer extends CanvasRenderer { public static measureText(style:TextStyle, text:string) { var measuredWidth, measuredHeight; var extendSize; helpContext.font = style.font; measuredWidth = Math.ceil(helpContext.measureText(text).width); measuredHeight = Math.ceil(helpContext.measureText("M").width*1.2); if(style.shadow || style.stroke) { extendSize = Math.max(style.strokeWidth, Math.abs(style.shadowOffsetX), Math.abs(style.shadowOffsetY)); measuredWidth += extendSize*2; measuredHeight += extendSize*2+4; } measuredWidth = Math.ceil(measuredWidth); measuredHeight = Math.ceil(measuredHeight); if(measuredWidth % 2 !== 0) { measuredWidth += 1; } if(measuredHeight % 2 !== 0) { measuredHeight += 1; } return { width: measuredWidth, height: measuredHeight }; } get text():string { return this._text; } set text(value:string) { if(typeof value !== 'string') { value = value + ''; } if(value === this._text) return; this._text = value; this._textDirty = true; } get textStyle():TextStyle { return this._textStyle; } set textStyle(value:TextStyle) { this._textStyle = value; this._textDirty = true; } get textWidth():number { return this._canvasSize.width; } get textHeight():number { return this._canvasSize.height; } _textDirty:boolean = true; _text:string; _textStyle:TextStyle = new TextStyle(); render(renderer: renderer.IRenderer, flags: number): void { var size; if(this._textDirty || this._textStyle.dirty) { size = this.measureTextSize(); this.canvasWidth = size.width; this.canvasHeight = size.height; this._textStyle.dirty = false; this._textDirty = false; this._graphicsDirty = true; } super.render(renderer, flags); } draw(context):void { this.drawText(context, this._canvasSize.width, this._canvasSize.height); } protected drawText(context, measuredWidth, measuredHeight) { context.save(); context.font = this._textStyle.font; context.textAlign = 'center'; context.textBaseline = 'middle'; if (this._textStyle.shadow && (this._textStyle.shadowOffsetX > 0 || this._textStyle.shadowOffsetY > 0)) { context.fillStyle = this._textStyle.shadowColor; context.fillText( this._text, measuredWidth / 2 + this._textStyle.shadowOffsetX, measuredHeight / 2 + this._textStyle.shadowOffsetY); } if (this._textStyle.stroke && this._textStyle.strokeWidth > 0) { context.strokeStyle = this._textStyle.strokeColor; context.lineWidth = this._textStyle.strokeWidth; context.strokeText(this._text, measuredWidth / 2, measuredHeight / 2); } context.fillStyle = this._textStyle.color; context.fillText(this._text, measuredWidth / 2, measuredHeight / 2); context.restore(); } protected measureTextSize() { var measureSize; if(!this._text) { measureSize = { width: 0, height: 0 }; } else { measureSize = TextRenderer.measureText(this._textStyle, this._text); } return measureSize; } protected generateCanvasTexture(renderer:renderer.IRenderer):void { var offset = { x: 0, y: 0 }; super.generateCanvasTexture(renderer); if(this._textStyle.align === TextStyle.CENTER) { offset.x = 0.5; } else if(this._textStyle.align === TextStyle.END) { offset.x = 1; } if(this._textStyle.baseline === TextStyle.MIDDLE) { offset.y = 0.5; } else if(this._textStyle.baseline === TextStyle.BOTTOM) { offset.y = 1; } this.setTextureOffset(offset); } } export class TextStyle { public static START = 'start'; public static CENTER = 'center'; public static END = 'end'; public static TOP = 'top'; public static MIDDLE = 'middle'; public static BOTTOM = 'bottom'; dirty:boolean = true; get font():string { return this._font; } set font(value:string) { if(value === this._font) return; this._font = value; this.dirty = true; } get color():string { return this._color; } set color(value:string) { if(value === this._color) return; this._color = value; this.dirty = true; } get shadow():boolean { return this._shadow; } set shadow(value:boolean) { if(value === this._shadow) return; this._shadow = value; this.dirty = true; } get shadowColor():string { return this._shadowColor; } set shadowColor(value:string) { this._shadowColor = value; this.dirty = true; } get shadowOffsetX():number { return this._shadowOffsetX; } set shadowOffsetX(value:number) { if(value === this._shadowOffsetX) return; this._shadowOffsetX = value; this.dirty = true; } get shadowOffsetY():number { return this._shadowOffsetY; } set shadowOffsetY(value:number) { if(value === this._shadowOffsetY) return; this._shadowOffsetY = value; this.dirty = true; } get stroke():boolean { return this._stroke; } set stroke(value:boolean) { if(value === this._stroke) return; this._stroke = value; this.dirty = true; } get strokeColor():string { return this._strokeColor; } set strokeColor(value:string) { if(value === this._strokeColor) return; this._strokeColor = value; this.dirty = true; } get strokeWidth():number { return this._strokeWidth; } set strokeWidth(value:number) { if(value === this._strokeWidth) return; this._strokeWidth = value; this.dirty = true; } get align():string { return this._align; } set align(value:string) { if(value === this._align) return; this._align = value; this.dirty = true; } get baseline():string { return this._baseline; } set baseline(value:string) { if(value === this._baseline) return; this._baseline = value; this.dirty = true; } _font:string = 'normal 24px Arial'; _color:string = '#000000'; _shadow:boolean = false; _shadowColor = '#000000'; _shadowOffsetX:number = 0; _shadowOffsetY:number = 0; _stroke:boolean = false; _strokeColor = '#000000'; _strokeWidth:number = 0; _align:string = TextStyle.START; _baseline:string = TextStyle.TOP; } Component.register(TextRenderer, { name: 'TextRenderer', properties: [{ name: 'text', type: 'string' }, { name: 'style', type: 'object', convert: PropertyConverter.json2TextStyle, editor: 'textStyle' }] }); }
zzm2q/WOZLLA.js
src/core/Time.ts
module WOZLLA { /** * @class WOZLLA.Time * @static */ export class Time { /** * @property {number} delta * @readonly * @static */ static delta:number = 0; /** * @property {number} now * @readonly * @static */ static now:number = 0; /** * @property {number} measuredFPS * @readonly * @static */ static measuredFPS:number = 0; static _nowIncrease:number = 0; public static update(timeScale) { var now = Date.now() + this._nowIncrease; if(this.now) { this.delta = (now - this.now) * timeScale; this._nowIncrease += this.delta * (timeScale - 1); this.now += this.delta; this.measuredFPS = 1000/this.delta; } else { this.now = now; this.delta = 1000/60; } } public static reset() { this.delta = 0; this.now = 0; this._nowIncrease = 0; this.measuredFPS = 0; } } }
zzm2q/WOZLLA.js
src/renderer/RenderCommandBase.ts
<reponame>zzm2q/WOZLLA.js<filename>src/renderer/RenderCommandBase.ts module WOZLLA.renderer { /** * @class WOZLLA.renderer.RenderCommandBase * @abstract */ export class RenderCommandBase implements IRenderCommand { get globalZ():number { return this._globalZ; } get layer():string { return this._layer; } _globalZ:number; _layer:string; _addIndex:number; constructor(globalZ:number, layer:string) { this._globalZ = globalZ; this._layer = layer; } } }
zzm2q/WOZLLA.js
extensions/DragonBones/WFactory.ts
<filename>extensions/DragonBones/WFactory.ts /// <reference path="../../libs/DragonBones.d.ts"/> /// <reference path="WSlot.ts"/> /// <reference path="WTextureAtlas.ts"/> /// <reference path="../../src/core/Scheduler.ts"/> /// <reference path="../../src/core/GameObject.ts"/> /// <reference path="../../src/component/renderer/SpriteRenderer.ts"/> module WOZLLA.DragonBones { var clockSetup = false; export function setupWorldClock() { if(clockSetup) { return; } clockSetup = true; WOZLLA.Director.getInstance().scheduler.scheduleLoop(function() { dragonBones.WorldClock.clock.advanceTime(1/60); }); } export class WFactory extends dragonBones.BaseFactory { constructor() { super(this); } /** @private */ public _generateArmature():dragonBones.Armature { var container = new WOZLLA.GameObject(); container.init(); return new dragonBones.Armature(container); } /** @private */ public _generateSlot():dragonBones.Slot { return new WSlot(); } /** @private */ public _generateDisplay(textureAtlas:WTextureAtlas, fullName:string, pivotX:number, pivotY:number):any { var gameObj = new WOZLLA.GameObject(); var spriteRenderer = new WOZLLA.component.SpriteRenderer(); spriteRenderer.sprite = textureAtlas.getSprite(fullName); spriteRenderer.spriteOffset = { x: pivotX/spriteRenderer.sprite.frame.width, y: pivotY/spriteRenderer.sprite.frame.height }; gameObj.addComponent(spriteRenderer); gameObj.init(); return gameObj; } } }
zzm2q/WOZLLA.js
src/utils/Ease.ts
module WOZLLA.utils { export class Ease { public static get(amount):Function { if (amount < -1) { amount = -1; } if (amount > 1) { amount = 1; } return function (t) { if (amount == 0) { return t; } if (amount < 0) { return t * (t * -amount + 1 + amount); } return t * ((2 - t) * amount + (1 - amount)); } } public static getPowIn(pow):Function { return function (t) { return Math.pow(t, pow); } } public static getPowOut(pow):Function { return function (t) { return 1 - Math.pow(1 - t, pow); } } public static getPowInOut(pow):Function { return function (t) { if ((t *= 2) < 1) return 0.5 * Math.pow(t, pow); return 1 - 0.5 * Math.abs(Math.pow(2 - t, pow)); } } public static quadIn = Ease.getPowIn(2); public static quadOut = Ease.getPowOut(2); public static quadInOut = Ease.getPowInOut(2); public static cubicIn = Ease.getPowIn(3); public static cubicOut = Ease.getPowOut(3); public static cubicInOut = Ease.getPowInOut(3); public static quartIn = Ease.getPowIn(4); public static quartOut = Ease.getPowOut(4); public static quartInOut = Ease.getPowInOut(4); public static quintIn = Ease.getPowIn(5); public static quintOut = Ease.getPowOut(5); public static quintInOut = Ease.getPowInOut(5); public static sineIn(t):number { return 1 - Math.cos(t * Math.PI / 2); } public static sineOut(t):number { return Math.sin(t * Math.PI / 2); } public static sineInOut(t):number { return -0.5 * (Math.cos(Math.PI * t) - 1) } public static getBackIn(amount):Function { return function (t) { return t * t * ((amount + 1) * t - amount); } } public static backIn = Ease.getBackIn(1.7); public static getBackOut(amount):Function { return function (t) { t = t - 1; return (t * t * ((amount + 1) * t + amount) + 1); } } public static backOut = Ease.getBackOut(1.7); public static getBackInOut(amount):Function { amount *= 1.525; return function (t) { if ((t *= 2) < 1) return 0.5 * (t * t * ((amount + 1) * t - amount)); return 0.5 * ((t -= 2) * t * ((amount + 1) * t + amount) + 2); } } public static backInOut = Ease.getBackInOut(1.7); public static circIn(t):number { return -(Math.sqrt(1 - t * t) - 1); } public static circOut(t):number { return Math.sqrt(1 - (t) * t); } public static circInOut(t):number { if ((t *= 2) < 1) { return -0.5 * (Math.sqrt(1 - t * t) - 1); } return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); } public static bounceIn(t):number { return 1 - Ease.bounceOut(1 - t); } public static bounceOut(t):number { if (t < 1 / 2.75) { return (7.5625 * t * t); } else if (t < 2 / 2.75) { return (7.5625 * (t -= 1.5 / 2.75) * t + 0.75); } else if (t < 2.5 / 2.75) { return (7.5625 * (t -= 2.25 / 2.75) * t + 0.9375); } else { return (7.5625 * (t -= 2.625 / 2.75) * t + 0.984375); } } public static bounceInOut(t):number { if (t < 0.5) return Ease.bounceIn(t * 2) * .5; return Ease.bounceOut(t * 2 - 1) * 0.5 + 0.5; } public static getElasticIn(amplitude, period):Function { var pi2 = Math.PI * 2; return function (t) { if (t == 0 || t == 1) return t; var s = period / pi2 * Math.asin(1 / amplitude); return -(amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period)); } } public static elasticIn = Ease.getElasticIn(1, 0.3); public static getElasticOut(amplitude, period):Function { var pi2 = Math.PI * 2; return function (t) { if (t == 0 || t == 1) return t; var s = period / pi2 * Math.asin(1 / amplitude); return (amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1); } } public static elasticOut = Ease.getElasticOut(1, 0.3); public static getElasticInOut(amplitude, period):Function { var pi2 = Math.PI * 2; return function (t) { var s = period / pi2 * Math.asin(1 / amplitude); if ((t *= 2) < 1) return -0.5 * (amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period)); return amplitude * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * pi2 / period) * 0.5 + 1; } } public static elasticInOut = Ease.getElasticInOut(1, 0.3 * 1.5); public static linear(t) { return t; } public static expoIn(time) { return time == 0 ? 0 : Math.pow(2, 10 * (time - 1)) - 0.001; } public static expoOut(time) { return time == 1 ? 1 : (-Math.pow(2, -10 * time) + 1); } public static expoInOut(time) { time /= 0.5; if (time < 1) { time = 0.5 * Math.pow(2, 10 * (time - 1)); } else { time = 0.5 * (-Math.pow(2, -10 * (time - 1)) + 2); } return time; } public static keyMap = { 0 : 'linear', 1 : 'sineIn', 2 : 'sineOut', 3 : 'sineInOut', 4 : 'quadIn', 5 : 'quadOut', 6 : 'quadInOut', 7 : 'cubicIn', 8 : 'cubicOut', 9 : 'cubicInOut', 10 : 'quartIn', 11 : 'quartOut', 12 : 'quartInOut', 13 : 'quintIn', 14 : 'quintOut', 15 : 'quintInOut', 16 : 'expoIn', 17 : 'expoOut', 18 : 'expoInOut', 19 : 'circIn', 20 : 'circOut', 21 : 'circInOut', 22 : 'elasticIn', 23 : 'elasticOut', 24 : 'elasticInOut', 25 : 'backIn', 26 : 'backOut', 27 : 'backInOut', 28 : 'bounceIn', 29 : 'bounceOut', 30 : 'bounceInOut' }; public static getByKey(key):any { return Ease[Ease.keyMap[key]]; } } }
zzm2q/WOZLLA.js
src/renderer/QuadCommand.ts
/// <reference path="ITexture.ts"/> /// <reference path="Quad.ts"/> /// <reference path="RenderCommandBase.ts"/> /// <reference path="ILayerManager.ts"/> /// <reference path="../utils/ObjectPool.ts"/> module WOZLLA.renderer { var quadCommandPool; /** * @class WOZLLA.renderer.QuadCommand * @extends WOZLLA.renderer.RenderCommandBase */ export class QuadCommand extends RenderCommandBase implements WOZLLA.utils.Poolable { public static init(globalZ:number, layer:string, texture:ITexture, materialId:string, quad:Quad):QuadCommand { var quadCommand = quadCommandPool.retain(); quadCommand.initWith(globalZ, layer, texture, materialId, quad); return quadCommand; } isPoolable:boolean = true; get texture():ITexture { return this._texture; } get materialId():string { return this._materialId; } get quad():Quad { return this._quad; } _texture:ITexture; _materialId:string; _quad:Quad; constructor(globalZ:number, layer:string) { super(globalZ, layer); } initWith(globalZ:number, layer:string, texture:ITexture, materialId:string, quad):void { this._globalZ = globalZ; this._layer = layer; this._texture = texture; this._materialId = materialId; this._quad = quad; } release() { quadCommandPool.release(this); } } quadCommandPool = new WOZLLA.utils.ObjectPool<QuadCommand>(200, ():QuadCommand => { return new QuadCommand(0, ILayerManager.DEFAULT); }); }
zzm2q/WOZLLA.js
src/assets/Sprite.ts
<reponame>zzm2q/WOZLLA.js module WOZLLA.assets { /** * an sprite is a part of a sprite atlas * @class WOZLLA.assets.Sprite * <br/> * see also: <br/> * {@link WOZLLA.assets.SpriteAtlas}<br/> */ export class Sprite { /** * get the sprite atlas of this sprite belongs to * @property {WOZLLA.assets.SpriteAtlas} spriteAltas * @readonly */ get spriteAtlas():SpriteAtlas { return this._spriteAtlas; } /** * get frame info * @property {any} frame * @readonly */ get frame():any { return this._frame; } /** * get sprite name * @property {string} name * @readonly */ get name():string { return this._name; } _spriteAtlas:SpriteAtlas; _frame:any; _name:string; /** * new a sprite * @method constructor * @param spriteAtlas * @param frame * @param name */ constructor(spriteAtlas:SpriteAtlas, frame, name?) { this._spriteAtlas = spriteAtlas; this._frame = frame; this._name = name; } } }
zzm2q/WOZLLA.js
extensions/PureMVC/AsyncCommand.ts
<reponame>zzm2q/WOZLLA.js ///<reference path='../../libs/puremvc-typescript-multicore-1.1.d.ts'/> module WOZLLA.PureMVC { export class AsyncCommand extends puremvc.SimpleCommand { public execute(notification: puremvc.INotification, onComplete?:Function): void { onComplete && onComplete(); } } }
zzm2q/WOZLLA.js
src/renderer/BlendType.ts
module WOZLLA.renderer { /** * @class WOZLLA.renderer.BlendType */ export class BlendType { public static NORMAL = 1; public static ADD = 2; public static MULTIPLY = 3; public static SCREEN = 4; get srcFactor():any { return this._srcFactor; } get distFactor():any { return this._distFactor; } _srcFactor; _distFactor; constructor(srcFactor, distFactor) { this._srcFactor = srcFactor; this._distFactor = distFactor; } applyBlend(gl) { gl.blendFunc(this._srcFactor, this._distFactor); } } }
zzm2q/WOZLLA.js
extensions/DragonBones/SkeletonRenderer.ts
<reponame>zzm2q/WOZLLA.js<gh_stars>0 module WOZLLA.DragonBones { export class SkeletonRenderer extends WOZLLA.Renderer { get skeletonSrc():string { return this._skeletonSrc; } set skeletonSrc(value:string) { this._skeletonSrc = value; } get textureSrc():string { return this._textureSrc; } set textureSrc(value:string) { this._textureSrc = value; } get armatureName():string { return this._armatureName; } set armatureName(value:string) { this._armatureName = value; } get armature():dragonBones.Armature { return this._armature; } _skeletonSrc; _textureSrc; _factory; _skeletonJSONAsset; _wTextureAtlas; _armatureName:string; _armature:dragonBones.Armature; _container:WOZLLA.GameObject; init() { this.initArmature(); super.init(); } destroy() { this._skeletonJSONAsset && this._skeletonJSONAsset.release(); this._skeletonJSONAsset = null; this._wTextureAtlas && this._wTextureAtlas.release(); this._wTextureAtlas = null; this._armature && this._armature.dispose(); this._armature = null; this._factory && this._factory.dispose(); if(this._container) { this._container.destroy(); this._container.removeMe(); this._container = null; } super.destroy(); } render(renderer:WOZLLA.renderer.IRenderer, flags:number):void { this._container.visit(renderer, this.transform, flags); } loadAssets(callback:Function) { var assetLoader; if(this._skeletonSrc && this._textureSrc && this._armatureName) { assetLoader = Director.getInstance().assetLoader; assetLoader.load(this._skeletonSrc, WOZLLA.assets.JSONAsset, () => { var jsonAsset = <WOZLLA.assets.JSONAsset>assetLoader.getAsset(this._skeletonSrc); if(!jsonAsset) { callback(); return; } jsonAsset.retain(); assetLoader.load(this._textureSrc, WTextureAtlas, () => { var wTextureAtlas = assetLoader.getAsset(this._textureSrc); if(!wTextureAtlas) { jsonAsset.release(); callback(); return; } wTextureAtlas.retain(); this._skeletonJSONAsset = jsonAsset; this._wTextureAtlas = wTextureAtlas; callback(); }); }); } else { callback(); } } protected initArmature() { var skeletonData, factory, armature, container; if(this._skeletonJSONAsset && this._wTextureAtlas && this._armatureName) { factory = new WFactory(); skeletonData = this._skeletonJSONAsset.cloneData(); factory.addSkeletonData(dragonBones.DataParser.parseDragonBonesData(skeletonData), skeletonData.name); factory.addTextureAtlas(this._wTextureAtlas, this._wTextureAtlas.name); armature = factory.buildArmature(this._armatureName); container = <WOZLLA.GameObject>armature.getDisplay(); dragonBones.WorldClock.clock.add(armature); setupWorldClock(); this._container = container; this._factory = factory; this._armature = armature; } } } }
zzm2q/WOZLLA.js
src/assets/SpriteAtlas.ts
<filename>src/assets/SpriteAtlas.ts /// <reference path="Sprite.ts"/> /// <reference path="../utils/Ajax.ts"/> module WOZLLA.assets { var imageTest = /(\.png|\.jpg)$/i; function isImageURL(url) { return imageTest.test(url); } function getFileName(url) { var idx = url.lastIndexOf('/'); if(idx !== -1) { return url.substr(idx+1, url.length); } return url; } /** * a sprite atlas contains many {@link WOZLLA.assets.Sprite}. * it's recommended to user {@link WOZLLA.assets.AssetLoader} to load SpriteAtlas. * @class WOZLLA.assets.SpriteAtlas * @extends WOZLLA.assets.GLTextureAsset * <br/> * see also: * {@link WOZLLA.assets.Sprite} * {@link WOZLLA.assets.AssetLoader} */ export class SpriteAtlas extends GLTextureAsset { /** * @property {string} imageSrc * @readonly */ get imageSrc():string { return this._imageSrc; } /** * an file url descript sprite atlas infos. * @property {string} metaSrc * @readonly */ get metaSrc():string { return this._metaSrc; } /** * @property {any} sourceImage * @readonly */ get sourceImage():any { return this._sourceImage; } /** * @property {any} spriteData * @readonly */ get spriteData():any { return this._spriteData; } _imageSrc:string; _metaSrc:string; _sourceImage; _entireSprite:Sprite; _spriteData:any; _spriteCache:any = {}; _frameLengthCache:number; getFrameLength():number { var frames; if(!this._spriteData) { return 1; } frames = this._spriteData.frames; if(Object.prototype.toString.call(frames) === '[object Array]') { return frames.length; } if(this._frameLengthCache == void 0) { this._frameLengthCache = 0; for(var _ in frames) { this._frameLengthCache ++; } } return this._frameLengthCache; } /** * get sprite by name * @param name * @returns {WOZLLA.assets.Sprite} */ getSprite(name?:any):Sprite { var frameData, sprite; if(name == void 0) { return this._entireSprite; } sprite = this._spriteCache[name]; if(sprite) { return sprite; } if(!this._spriteData) { return null; } frameData = this._spriteData.frames[name]; if(frameData) { if(typeof frameData.frame.width === 'undefined') { frameData.frame.width = frameData.frame.w; frameData.frame.height = frameData.frame.h; } sprite = new Sprite(this, { x: frameData.frame.x, y: frameData.frame.y, width: frameData.frame.width, height: frameData.frame.height, offsetX: Math.ceil(frameData.spriteSourceSize ? (frameData.spriteSourceSize.x || 0) : 0), offsetY: Math.ceil(frameData.spriteSourceSize ? (frameData.spriteSourceSize.y || 0) : 0) }, name); this._spriteCache[name] = sprite; return sprite; } return null; } /** * load this asset * @param onSuccess * @param onError */ load(onSuccess:()=>any, onError:(error)=>any) { if(isImageURL(this.fullPath)) { this._imageSrc = this.fullPath; this._loadImage((error, image) => { if(error) { onError && onError(error); } else { this._generateTexture(image); this._sourceImage = image; this._entireSprite = new Sprite(this, { x: 0, y: 0, width: image.width, height: image.height }); onSuccess && onSuccess(); } }); } else { this._metaSrc = this.fullPath; this._loadSpriteAtlas((error, image, spriteData) => { if(error) { onError && onError(error); } else { this._sourceImage = image; this._generateTexture(image); this._entireSprite = new Sprite(this, { x: 0, y: 0, width: image.width, height: image.height }); this._spriteData = spriteData; onSuccess && onSuccess(); } }); } } _loadImage(callback:(error:string, image?)=>any) { var image = new Image(); image.src = this._imageSrc; image.onload = () => { callback && callback(null, image); }; image.onerror = () => { callback('Fail to load image: ' + this._imageSrc); }; } _loadSpriteAtlas(callback:(error:string, image?, spriteData?)=>any) { var me = this; WOZLLA.utils.Ajax.request({ url: me._metaSrc, dataType: 'json', success: function(data:any) { var imageSuffix = data.meta.image; var metaFileName = getFileName(me._metaSrc); me._imageSrc = me._metaSrc.replace(new RegExp(metaFileName + '$'), imageSuffix); me._loadImage(function(error, image) { if(error) { callback && callback(error); } else { callback && callback(null, image, data); } }); }, error : function(err) { callback('Fail to load sprite: ' + this._metaSrc + ', ' + err.code + ':' + err.message); } }); } } }
zzm2q/WOZLLA.js
src/renderer/internal/ShaderManager.ts
<filename>src/renderer/internal/ShaderManager.ts /// <reference path="ShaderProgram.ts"/> /// <reference path="../IShaderProgram.ts"/> /// <reference path="../shader/V2T2C1A1.ts"/> /// <reference path="../WebGLUtils.ts"/> module WOZLLA.renderer { /** * @class WOZLLA.renderer.ShaderManager * @extends WOZLLA.renderer.IShaderManager */ export class ShaderManager implements IShaderManager { _gl:any; _shaderMap:any; constructor(gl) { this._gl = gl; this._shaderMap = {}; this._shaderMap[IShaderProgram.V2T2C1A1] = this.createShaderProgram( shader.V2T2C1A1.VERTEX_SOURCE, shader.V2T2C1A1.FRAGMENT_SOURCE, shader.V2T2C1A1); } getShaderProgram(id):IShaderProgram { return this._shaderMap[id]; } createShaderProgram(vertexSource:string, fragmentSource:string, ShaderClass:Function=ShaderProgram):IShaderProgram { var result = WebGLUtils.compileProgram(this._gl, vertexSource, fragmentSource); var shaderProgram = <IShaderProgram>new (<any>ShaderClass)(result.program, result.vertexShader, result.fragmentShader); this._shaderMap[shaderProgram.id] = shaderProgram; return shaderProgram; } deleteShaderProgram(shaderProgram:IShaderProgram):void { this._gl.deleteProgram(shaderProgram.id); this._gl.deleteShader(shaderProgram.vertexShader); this._gl.deleteShader(shaderProgram.fragmentShader); delete this._shaderMap[shaderProgram.id]; } clear():void { for(var id in this._shaderMap) { this.deleteShaderProgram(this._shaderMap[id]); } } } }